Esempio n. 1
0
 private function _sendPayment($marker, $marks, $assessmentAssoc, $assessmentFix = 0)
 {
     if (count($marks) === 0 && empty($assessmentAssoc)) {
         return false;
     }
     foreach ($marks as $markAssoc) {
         $mark = new Mark();
         $mark->setKey($markAssoc[$mark->getKeyField()]);
         $mark->paid();
         $mark->update();
         $markKeys[] = $markAssoc[$mark->getKeyField()];
     }
     $assessmentAmount = 0;
     if (!empty($assessmentAssoc)) {
         $assessment = new Assessment();
         $assessment->setKey($assessmentAssoc[$assessment->getKeyField()]);
         $assessment->paid();
         $assessment->update();
         $markKeys[] = 'Assessment script';
         $assessmentAmount = 1;
     }
     if ($assessmentFix) {
         $assessmentFix = new AssessmentFix();
         $assessmentFix->setKey($this->_getUser());
         $assessmentFix->paid();
         $assessmentFix->update();
         $markKeys[] = 'Assessment bounty';
     }
     $this->load->model('wage');
     $amount = ($assessmentFix + count($marks) + $assessmentAmount) * 1.5;
     $wage = new Wage();
     $wage->paid($marker, $amount, $markKeys);
     $wage->create();
     return $amount;
 }
 public function seedUnits($batches, $allStudents, $collegeid)
 {
     foreach ($batches as $batch) {
         $students = $allStudents[$batch];
         $totalUnderload = 0;
         $totalNodata = 0;
         foreach ($students as $student) {
             $units = Assessment::getOneAveUnitsCollege($student->studentid, $collegeid);
             if ($units === -1) {
                 $totalNodata++;
             } else {
                 if ($units < 15) {
                     $totalUnderload++;
                 } else {
                 }
             }
         }
         $newCorrelation = new Correlation();
         $newCorrelation->factorid = 6;
         $newCorrelation->batch = $batch;
         $countStudents = count($students);
         if ($countStudents - $totalNodata > 0) {
             $newCorrelation->ratio = $totalUnderload / ($countStudents - $totalNodata);
         } else {
             $newCorrelation->ratio = 0;
         }
         $newCorrelation->unittype = 'college';
         $newCorrelation->collegeid = $collegeid;
         $newCorrelation->save();
     }
 }
 public function alterUnits($batches, $allStudents, $programid)
 {
     foreach ($batches as $batch) {
         $students = $allStudents[$batch];
         $totalUnderload = 0;
         $totalNodata = 0;
         foreach ($students as $student) {
             $units = Assessment::getOneAveUnitsProgram($student->studentid, $programid);
             if ($units === -1) {
                 $totalNodata++;
             } else {
                 if ($units < 15) {
                     $totalUnderload++;
                 } else {
                 }
             }
         }
         $entry = Correlation::where('batch', $batch)->where('unittype', 'program')->where('programid', $programid)->where('factorid', 6)->first();
         $countStudents = count($students);
         if ($countStudents - $totalNodata > 0) {
             $entry->ratio = $totalUnderload / ($countStudents - $totalNodata);
         } else {
             $entry->ratio = 0;
         }
         $entry->save();
     }
 }
 /**
  * Run the migrations.
  *
  * @return void
  */
 public function up()
 {
     Schema::table('correlations', function (Blueprint $table) {
         //
     });
     $batches = [2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009];
     foreach ($batches as $batch) {
         $students = Studentterm::getBatchStudents($batch * 100000);
         $totalUnderload = 0;
         $totalNodata = 0;
         foreach ($students as $student) {
             $units = Assessment::getOneAveUnits($student->studentid);
             if ($units === -1) {
                 $totalNodata++;
             } else {
                 if ($units < 15) {
                     $totalUnderload++;
                 } else {
                 }
             }
         }
         $newEntry = new Correlation();
         $newEntry->factorid = 6;
         $newEntry->batch = $batch;
         $newEntry->ratio = $totalUnderload / (count($students) - $totalNodata);
         $newEntry->save();
     }
 }
Esempio n. 5
0
 public function getGrade(\DOMElement $context)
 {
     $score = array_reduce(['quizzes', 'projects', 'discourse', 'practice'], function ($carry, $item) {
         return $carry + $this->{$item}['score'];
     }, 0);
     $apr = $score > 96 ? 'over' : ($score <= 70 ? 'under' : 'meet');
     return new \bloc\types\Dictionary(['score' => $score, 'letter' => Assessment::LETTER($score, 100), 'apr' => $apr]);
 }
Esempio n. 6
0
 /**
  * Returns list of assessments for Flex.
  *
  */
 function assessments()
 {
     $this->load->model('assessment');
     $script = new Assessment();
     $query = $script->getSubmittedAssessments();
     if (!$query instanceof CI_DB_mysql_result) {
         throw new Exception('Did not return a result object(?!)');
     }
     if ($query->num_rows() > 0) {
         $results = $query->result_array();
         foreach ($results as $assessment) {
             $explodeAroundPipe = explode('|', $assessment['pageKeys']);
             $assessment['pages'] = count($explodeAroundPipe);
             unset($assessment['pageKeys']);
             $assessments[] = $assessment;
         }
         $this->load->library('json');
         $assessments = $this->json->encode($assessments);
     } else {
         $assessments = '{}';
     }
     $this->load->view('user/marked_assessments', array('assessments' => $assessments));
 }
Esempio n. 7
0
 public function addMark()
 {
     if (!($jsonData = $this->input->post('jsonData'))) {
         die('null');
     }
     $this->load->model('assessment');
     $this->load->model('script');
     $this->load->library('json');
     $decoded = $this->json->decode($jsonData);
     $assessment = new Assessment();
     $assessment->setKey($decoded->script);
     $assessment->set('marker', $this->session->userdata($this->_sessionAuthVar));
     $assessment->set('markData', $jsonData);
     $assessment->set('targets', serialize($decoded->targets));
     $assessment->set('generalComment', $decoded->generalComment);
     $assessment->set('status', Assessment::UNPAID);
     if ($assessment->create()) {
         $this->_flexResult(I_FlexMarksIn::SAVE_SUCCESSFUL);
     } else {
         $this->_flexResult(I_FlexIO::ERROR);
     }
 }
 public function seedOverload($batches, $allStudents)
 {
     foreach ($batches as $batch) {
         $students = $allStudents[$batch];
         $totalOverload = 0;
         $totalNodata = 0;
         foreach ($students as $student) {
             $units = Assessment::getOneAveUnits($student->studentid);
             if ($units === -1) {
                 $totalNodata++;
             } else {
                 if ($units > 18) {
                     $totalOverload++;
                 } else {
                 }
             }
         }
         $newCorrelation = new Correlation();
         $newCorrelation->factorid = 9;
         $newCorrelation->batch = $batch;
         $newCorrelation->ratio = $totalOverload / (count($students) - $totalNodata);
         $newCorrelation->save();
     }
 }
Esempio n. 9
0
 /**
  * Deletes an assessment.
  */
 private function _delete($iSurveyID, $assessmentId)
 {
     if (Permission::model()->hasSurveyPermission($iSurveyID, 'assessments', 'delete')) {
         Assessment::model()->deleteAllByAttributes(array('id' => $assessmentId, 'sid' => $iSurveyID));
     }
 }
function assessment_controller()
{
    global $session, $route, $mysqli;
    // -------------------------------------------------------------------------
    // Check if session has been authenticated, if not redirect to login page (html)
    // or send back "false" (json)
    // -------------------------------------------------------------------------
    if (!$session['read']) {
        if ($route->format == 'html') {
            $result = view("Modules/user/login_block.php", array());
        } else {
            $result = "Not logged";
        }
        return array('content' => $result);
    }
    // -------------------------------------------------------------------------
    // Session is authenticated so we run the action
    // -------------------------------------------------------------------------
    $result = false;
    if ($route->format == 'html') {
        if ($route->action == "view" && $session['write']) {
            $result = view("Modules/assessment/view.php", array());
        }
        if ($route->action == "list" && $session['write']) {
            $result = view("Modules/assessment/projects.php", array());
        }
    }
    if ($route->format == 'json') {
        require "Modules/assessment/assessment_model.php";
        $assessment = new Assessment($mysqli);
        require "Modules/assessment/organisation_model.php";
        $organisation = new Organisation($mysqli);
        // -------------------------------------------------------------------------------------------------------------
        // Create assessment
        // -------------------------------------------------------------------------------------------------------------
        if ($route->action == 'create' && $session['write']) {
            $result = $assessment->create($session['userid'], get('name'), get('description'));
            if (isset($_GET['org'])) {
                $orgid = (int) $_GET['org'];
                $assessment->org_access($result['id'], $orgid, 1);
            }
        }
        // -------------------------------------------------------------------------------------------------------------
        // List assessments
        // -------------------------------------------------------------------------------------------------------------
        if ($route->action == 'list' && $session['write']) {
            if (isset($_GET['orgid'])) {
                $orgid = $_GET['orgid'];
                $result = $assessment->get_org_list($orgid);
            } else {
                $result = $assessment->get_list($session['userid']);
            }
        }
        if ($route->action == 'delete' && $session['write']) {
            $result = $assessment->delete($session['userid'], get('id'));
        }
        if ($route->action == 'share' && $session['write']) {
            $result = $assessment->share($session['userid'], get('id'), get('username'));
        }
        if ($route->action == 'getshared' && $session['write']) {
            $result = $assessment->getshared($session['userid'], get('id'));
        }
        if ($route->action == 'get' && $session['write']) {
            $result = $assessment->get($session['userid'], get('id'));
        }
        if ($route->action == 'setstatus' && $session['write']) {
            if (isset($_GET['status'])) {
                $status = $_GET['status'];
                $result = $assessment->set_status($session['userid'], get('id'), $status);
            }
        }
        if ($route->action == 'setdata' && $session['write']) {
            $data = null;
            if (isset($_POST['data'])) {
                $data = $_POST['data'];
            }
            if (!isset($_POST['data']) && isset($_GET['data'])) {
                $data = $_GET['data'];
            }
            if ($data && $data != null) {
                $result = $assessment->set_data($session['userid'], post('id'), $data);
            }
        }
        if ($route->action == 'setnameanddescription' && $session['write']) {
            $name = null;
            if (isset($_POST['name'])) {
                $name = $_POST['name'];
            }
            if (!isset($_POST['name']) && isset($_GET['name'])) {
                $name = $_GET['name'];
            }
            $description = null;
            if (isset($_POST['description'])) {
                $description = $_POST['description'];
            }
            if (!isset($_POST['description']) && isset($_GET['description'])) {
                $description = $_GET['description'];
            }
            if ($name && $name != null && $description && $description != null) {
                $result = $assessment->set_name_and_description($session['userid'], post('id'), $name, $description);
            }
        }
        // -------------------------------------------------------------------------------------------------------------
        // Organisation
        // -------------------------------------------------------------------------------------------------------------
        if ($route->action == 'neworganisation' && $session['write'] && isset($_GET['orgname'])) {
            $orgname = $_GET['orgname'];
            $orgid = $organisation->create($orgname, $session['userid']);
            if ($orgid) {
                $result = array("success" => true, "myorganisations" => $organisation->get_organisations($session['userid']));
            } else {
                $result = array("success" => false, "message" => 'Organisation "' . $orgname . '" already exists!');
            }
        }
        if ($route->action == 'getorganisations' && $session['write']) {
            $result = $organisation->get_organisations($session['userid']);
        }
        if ($route->action == "organisationaddmember" && $session['write']) {
            $orgid = (int) $_GET['orgid'];
            $username = $_GET['membername'];
            global $user;
            if ($userid = $user->get_id($username)) {
                if ($organisation->add_member($orgid, $userid)) {
                    $result = array("success" => true, 'userid' => $userid, 'name' => $username, 'lastactive' => "?");
                } else {
                    $result = array("success" => false, "message" => 'Sorry, user "' . $username . '" is already a member');
                }
            } else {
                $result = array("success" => false, "message" => 'Sorry, user "' . $username . '" does not exist!?');
            }
        }
        if ($route->action == 'listlibrary' && $session['write']) {
            $result = $assessment->listlibrary($session['userid']);
        }
        if ($route->action == 'newlibrary' && $session['write']) {
            $result = $assessment->newlibrary($session['userid'], get('name'));
        }
        // Save library
        if ($route->action == 'savelibrary' && $session['write'] && isset($_POST['data'])) {
            $result = $assessment->savelibrary($session['userid'], post('id'), $_POST['data']);
        }
        if ($route->action == 'loadlibrary' && $session['write']) {
            $result = $assessment->loadlibrary($session['userid'], get('id'));
        }
        if ($route->action == 'sharelibrary' && $session['write']) {
            $result = $assessment->sharelibrary($session['userid'], get('id'), get('name'));
        }
        if ($route->action == 'getsharedlibrary' && $session['write']) {
            $result = $assessment->getsharedlibrary($session['userid'], get('id'));
        }
        // -------------------------------------------------------------------------------------------------------------
        // Image gallery
        // -------------------------------------------------------------------------------------------------------------
        if ($route->action == 'uploadimages' && $session['write']) {
            $result = $assessment->saveimages($session['userid'], post('id'), $_FILES);
        }
        if ($route->action == 'deleteimage' && $session['write']) {
            $result = $assessment->deleteimage($session['userid'], post('id'), post('filename'));
        }
        // Upgrade (temporary)
        /*
         if ($route->action == "upgrade" && $session['admin'])
         {
         $result = $mysqli->query("SELECT id, userid, author FROM assessment");
         $out = array();
         while ($row = $result->fetch_object()) {
         $out[] = $row;
         $assessment->access($row->id,$row->userid,1);
         }
         $result = $out;
         }
        */
    }
    return array('content' => $result, 'fullwidth' => true);
}
Esempio n. 11
0
 /**
  * Deletes a survey and all its data
  *
  * @access public
  * @param int $iSurveyID
  * @param bool @recursive
  * @return void
  */
 public function deleteSurvey($iSurveyID, $recursive = true)
 {
     Survey::model()->deleteByPk($iSurveyID);
     if ($recursive == true) {
         if (tableExists("{{survey_" . intval($iSurveyID) . "}}")) {
             Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "}}");
         }
         if (tableExists("{{survey_" . intval($iSurveyID) . "_timings}}")) {
             Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "_timings}}");
         }
         if (tableExists("{{tokens_" . intval($iSurveyID) . "}}")) {
             Yii::app()->db->createCommand()->dropTable("{{tokens_" . intval($iSurveyID) . "}}");
         }
         $oResult = Questions::model()->findAllByAttributes(array('sid' => $iSurveyID));
         foreach ($oResult as $aRow) {
             Answers::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Conditions::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Question_attributes::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Defaultvalues::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
         }
         Questions::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Assessment::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Groups::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Surveys_languagesettings::model()->deleteAllByAttributes(array('surveyls_survey_id' => $iSurveyID));
         Survey_permissions::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Saved_control::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Survey_url_parameters::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Quota::model()->deleteQuota(array('sid' => $iSurveyID), true);
     }
 }
Esempio n. 12
0
     }
     $period_reminder = $term . " of " . $year . " SESSION";
     //END HEADER PANEL SELECTS
     if ($id = $student->getAssessmentId($get_year, $get_term)) {
         $assessment = new Assessment($id);
         $c_t_id = $assessment->getAssessment()['teacher_id'];
         $c_teacher = new User($c_t_id);
         $scores = $assessment->getScores();
         //print_r($scores);
     }
 } else {
     //FOR THE HEADER PANEL SELECTS
     $year = null;
     $term = null;
     $assessment;
     if ($assessment = new Assessment($student->getLastAssessmentId())) {
         $current_session = $assessment->getYear();
         $current_term = $assessment->getTermID();
     }
     foreach ($sessions as $key => $value) {
         if ($value == $current_session) {
             $options .= "<option selected value=\"{$value}\">{$value} SESSION</option>";
             $year = $value;
         } else {
             $options .= "<option value=\"{$value}\">{$value} SESSION</option>";
         }
     }
     foreach ($terms as $key => $value) {
         if ($value['term_id'] == $current_term) {
             $options1 .= "<option selected value=\"{$value['term_id']}\">{$value['nice_name']}</option>";
             $term = $value['nice_name'];
Esempio n. 13
0
 protected function timeline_new()
 {
     $pid = Session::get('pid');
     $json = array();
     $date_arr = array();
     $query0 = DB::table('encounters')->where('pid', '=', $pid)->where('addendum', '=', 'n')->get();
     if ($query0) {
         foreach ($query0 as $row0) {
             $description = '';
             $procedureInfo = Procedure::find($row0->eid);
             if ($procedureInfo) {
                 $description .= '<span class="nosh_bold">Procedures:</span>';
                 if ($procedureInfo->proc_type != '') {
                     $description .= '<strong>Procedure: </strong>';
                     $description .= nl2br($procedureInfo->proc_type);
                 }
             }
             $assessmentInfo = Assessment::find($row0->eid);
             if ($assessmentInfo) {
                 if ($assessmentInfo->assessment_1 != '') {
                     $description .= '<span class="nosh_bold">Assessment:</span>';
                     $description .= '<br><strong>' . $assessmentInfo->assessment_1 . '</strong><br />';
                     if ($assessmentInfo->assessment_2 == '') {
                         $description .= '<br />';
                     }
                 }
                 if ($assessmentInfo->assessment_2 != '') {
                     $description .= '<strong>' . $assessmentInfo->assessment_2 . '</strong><br />';
                     if ($assessmentInfo->assessment_3 == '') {
                         $description .= '<br />';
                     }
                 }
                 if ($assessmentInfo->assessment_3 != '') {
                     $description .= '<strong>' . $assessmentInfo->assessment_3 . '</strong><br />';
                     if ($assessmentInfo->assessment_4 == '') {
                         $description .= '<br />';
                     }
                 }
                 if ($assessmentInfo->assessment_4 != '') {
                     $description .= '<strong>' . $assessmentInfo->assessment_4 . '</strong><br />';
                     if ($assessmentInfo->assessment_5 == '') {
                         $description .= '<br />';
                     }
                 }
                 if ($assessmentInfo->assessment_5 != '') {
                     $description .= '<strong>' . $assessmentInfo->assessment_5 . '</strong><br />';
                     if ($assessmentInfo->assessment_6 == '') {
                         $description .= '<br />';
                     }
                 }
                 if ($assessmentInfo->assessment_6 != '') {
                     $description .= '<strong>' . $assessmentInfo->assessment_6 . '</strong><br />';
                     if ($assessmentInfo->assessment_7 == '') {
                         $description .= '<br />';
                     }
                 }
                 if ($assessmentInfo->assessment_7 != '') {
                     $description .= '<strong>' . $assessmentInfo->assessment_7 . '</strong><br />';
                     if ($assessmentInfo->assessment_8 == '') {
                         $description .= '<br />';
                     }
                 }
                 if ($assessmentInfo->assessment_8 != '') {
                     $description .= '<strong>' . $assessmentInfo->assessment_8 . '</strong><br /><br />';
                 }
                 if ($assessmentInfo->assessment_other != '') {
                     if ($row0->encounter_template == 'standardmtm') {
                         $description .= '<br /><strong>SOAP Note: </strong>';
                     } else {
                         $description .= '<br /><strong>Additional Diagnoses: </strong>';
                     }
                     $description .= nl2br($assessmentInfo->assessment_other);
                     $description .= '<br /><br />';
                 }
                 if ($assessmentInfo->assessment_ddx != '') {
                     if ($row0->encounter_template == 'standardmtm') {
                         $description .= '<br /><strong>MAP2: </strong>';
                     } else {
                         $description .= '<br /><strong>Differential Diagnoses Considered: </strong>';
                     }
                     $description .= nl2br($assessmentInfo->assessment_ddx);
                     $description .= '<br /><br />';
                 }
                 if ($assessmentInfo->assessment_notes != '') {
                     if ($row0->encounter_template == 'standardmtm') {
                         $description .= '<br /><strong>Pharmacist Note: </strong>';
                     } else {
                         $description .= '<br /><strong>Assessment Discussion: </strong>';
                     }
                     $description .= nl2br($assessmentInfo->assessment_notes);
                     $description .= '<br /><br />';
                 }
             }
             $div0 = $this->timeline_item($row0->eid, 'eid', 'Encounter', $this->human_to_unix($row0->encounter_DOS), 'Encounter: ' . $row0->encounter_cc, $description, $row0->encounter_signed);
             $json[] = array('div' => $div0, 'startDate' => $this->human_to_unix($row0->encounter_DOS));
             $date_arr[] = $this->human_to_unix($row0->encounter_DOS);
         }
     }
     $query1 = DB::table('t_messages')->where('pid', '=', $pid)->get();
     if ($query1) {
         foreach ($query1 as $row1) {
             $div1 = $this->timeline_item($row1->t_messages_id, 't_messages_id', 'Telephone Message', $this->human_to_unix($row1->t_messages_dos), 'Telephone Message', substr($row1->t_messages_message, 0, 500) . '...', $row1->t_messages_signed);
             $json[] = array('div' => $div1, 'startDate' => $this->human_to_unix($row1->t_messages_dos));
             $date_arr[] = $this->human_to_unix($row1->t_messages_dos);
         }
     }
     $query2 = DB::table('rx_list')->where('pid', '=', $pid)->orderBy('rxl_date_active', 'asc')->groupBy('rxl_medication')->get();
     if ($query2) {
         foreach ($query2 as $row2) {
             $row2a = DB::table('rx_list')->where('rxl_id', '=', $row2->rxl_id)->first();
             if ($row2->rxl_sig == '') {
                 $instructions = $row2->rxl_instructions;
             } else {
                 $instructions = $row2->rxl_sig . ' ' . $row2->rxl_route . ' ' . $row2->rxl_frequency;
             }
             $description2 = $row2->rxl_medication . ' ' . $row2->rxl_dosage . ' ' . $row2->rxl_dosage_unit . ', ' . $instructions . ' for ' . $row2->rxl_reason;
             $div2 = $this->timeline_item($row2->rxl_id, 'rxl_id', 'New Medication', $this->human_to_unix($row2->rxl_date_active), 'New Medication', $description2);
             $json[] = array('div' => $div2, 'startDate' => $this->human_to_unix($row2->rxl_date_active));
             $date_arr[] = $this->human_to_unix($row2->rxl_date_active);
         }
     }
     $query3 = DB::table('issues')->where('pid', '=', $pid)->get();
     if ($query3) {
         foreach ($query3 as $row3) {
             if ($row3->type == 'Problem List') {
                 $title = 'New Problem';
             }
             if ($row3->type == 'Medical History') {
                 $title = 'New Medical Event';
             }
             if ($row3->type == 'Problem List') {
                 $title = 'New Surgical Event';
             }
             $div3 = $this->timeline_item($row3->issue_id, 'issue_id', $title, $this->human_to_unix($row3->issue_date_active), $title, $row3->issue);
             $json[] = array('div' => $div3, 'startDate' => $this->human_to_unix($row3->issue_date_active));
             $date_arr[] = $this->human_to_unix($row3->issue_date_active);
         }
     }
     $query4 = DB::table('immunizations')->where('pid', '=', $pid)->get();
     if ($query4) {
         foreach ($query4 as $row4) {
             $div4 = $this->timeline_item($row4->imm_id, 'imm_id', 'Immunization Given', $this->human_to_unix($row4->imm_date), 'Immunization Given', $row4->imm_immunization);
             $json[] = array('div' => $div4, 'startDate' => $this->human_to_unix($row4->imm_date));
             $date_arr[] = $this->human_to_unix($row4->imm_date);
         }
     }
     $query5 = DB::table('rx_list')->where('pid', '=', $pid)->where('rxl_date_inactive', '!=', '0000-00-00 00:00:00')->get();
     if ($query5) {
         foreach ($query5 as $row5) {
             $row5a = DB::table('rx_list')->where('rxl_id', '=', $row5->rxl_id)->first();
             if ($row5->rxl_sig == '') {
                 $instructions5 = $row5->rxl_instructions;
             } else {
                 $instructions5 = $row5->rxl_sig . ' ' . $row5->rxl_route . ' ' . $row5->rxl_frequency;
             }
             $description5 = $row5->rxl_medication . ' ' . $row5->rxl_dosage . ' ' . $row5->rxl_dosage_unit . ', ' . $instructions5 . ' for ' . $row5->rxl_reason;
             $div5 = $this->timeline_item($row5->rxl_id, 'rxl_id', 'Medication Stopped', $this->human_to_unix($row5->rxl_date_inactive), 'Medication Stopped', $description5);
             $json[] = array('div' => $div5, 'startDate' => $this->human_to_unix($row5->rxl_date_inactive));
             $date_arr[] = $this->human_to_unix($row5->rxl_date_inactive);
         }
     }
     $query6 = DB::table('allergies')->where('pid', '=', $pid)->where('allergies_date_inactive', '=', '0000-00-00 00:00:00')->get();
     if ($query6) {
         foreach ($query6 as $row6) {
             $div6 = $this->timeline_item($row6->allergies_id, 'allergies_id', 'New Allergy', $this->human_to_unix($row6->allergies_date_active), 'New Allergy', $row6->allergies_med);
             $json[] = array('div' => $div6, 'startDate' => $this->human_to_unix($row6->allergies_date_active));
             $date_arr[] = $this->human_to_unix($row6->allergies_date_active);
         }
     }
     foreach ($json as $key => $value) {
         $item[$key] = $value['startDate'];
     }
     array_multisort($item, SORT_DESC, $json);
     asort($date_arr);
     $arr['start'] = reset($date_arr);
     $arr['end'] = end($date_arr);
     if ($arr['end'] - $arr['start'] >= 315569260) {
         $arr['granular'] = 'decade';
     }
     if ($arr['end'] - $arr['start'] > 31556926 && $arr['end'] - $arr['start'] < 315569260) {
         $arr['granular'] = 'year';
     }
     if ($arr['end'] - $arr['start'] <= 31556926) {
         $arr['granular'] = 'month';
     }
     $arr['json'] = $json;
     return $arr;
 }
Esempio n. 14
0
<?php

include "../../includes/functions.inc";
if (Tools::valuePost("action") == "set") {
    $scores = Tools::valuePost("scores");
    $scores = explode(",", $scores);
    //print_r($raw_scores);
    $assID = 'NULL';
    if (Tools::valuePost("assID")) {
        //THIS IS TO UPDATE EXISTING ASSESSMENTS
        $assessment = new Assessment(Tools::valuePost("assID"));
        //$assessment->getClassID();
        $ass_class = new SchoolClass($assessment->getClassID());
        $subjects = $ass_class->getSubjectsID();
        $assessment->setScores($scores);
    } else {
        //THIS IS TO INSERT NEW ASSESSMENTS
        $student = new Student(Tools::valuePost("student"));
        if ($ass_id = $student->addAssessment($user->getID(), Tools::valuePost("year"), Tools::valuePost("term"))) {
            $assessment = new Assessment($ass_id);
            $assessment->setScores($scores);
            echo $ass_id;
        }
    }
}
if (Tools::valuePost("action") == "delete") {
    $assessment = new Assessment(Tools::valuePost("id"));
    $assessment->delete();
}
Esempio n. 15
0
 public static function getOneAveUnitsCollege($studentid, $collegeid)
 {
     $programids = Assessment::getCollPrograms($collegeid);
     $semesters = Assessment::select('total_units', 'aysem')->where('studentid', $studentid)->get();
     $totalUnits = 0;
     $totalSemesters = 0;
     $aysemGet = Studentterm::select('aysem')->where('studentid', $studentid)->whereIn('programid', $programids)->get();
     $aysems = [];
     foreach ($aysemGet as $aysem) {
         array_push($aysems, $aysem->aysem);
     }
     foreach ($semesters as $semester) {
         $semesterAysem = $semester->aysem;
         if (in_array($semesterAysem, $aysems) && (substr($semesterAysem, -1) === '1' || substr($semesterAysem, -1) === '2')) {
             $units = $semester->total_units;
             if ($units > 0 && $units <= 21) {
                 $totalUnits = $totalUnits + $units;
                 $totalSemesters = $totalSemesters + 1;
             }
         }
     }
     if ($totalSemesters > 0) {
         return $totalUnits / $totalSemesters;
     } else {
         return -1;
     }
 }
Esempio n. 16
0
/**
* This function imports a LimeSurvey .lss survey XML file
*
* @param mixed $sFullFilepath  The full filepath of the uploaded file
*/
function XMLImportSurvey($sFullFilepath, $sXMLdata = NULL, $sNewSurveyName = NULL, $iDesiredSurveyId = NULL, $bTranslateInsertansTags = true)
{
    Yii::app()->loadHelper('database');
    $clang = Yii::app()->lang;
    $aGIDReplacements = array();
    if ($sXMLdata == NULL) {
        $xml = simplexml_load_file($sFullFilepath);
    } else {
        $xml = simplexml_load_string($sXMLdata);
    }
    if ($xml->LimeSurveyDocType != 'Survey') {
        $results['error'] = $clang->gT("This is not a valid LimeSurvey survey structure XML file.");
        return $results;
    }
    $iDBVersion = (int) $xml->DBVersion;
    $aQIDReplacements = array();
    $aQuotaReplacements = array();
    $results['defaultvalues'] = 0;
    $results['answers'] = 0;
    $results['surveys'] = 0;
    $results['questions'] = 0;
    $results['subquestions'] = 0;
    $results['question_attributes'] = 0;
    $results['groups'] = 0;
    $results['assessments'] = 0;
    $results['quota'] = 0;
    $results['quotals'] = 0;
    $results['quotamembers'] = 0;
    $results['survey_url_parameters'] = 0;
    $results['importwarnings'] = array();
    $aLanguagesSupported = array();
    foreach ($xml->languages->language as $language) {
        $aLanguagesSupported[] = (string) $language;
    }
    $results['languages'] = count($aLanguagesSupported);
    // Import surveys table ====================================================
    foreach ($xml->surveys->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        $iOldSID = $results['oldsid'] = $insertdata['sid'];
        if ($iDesiredSurveyId != NULL) {
            $insertdata['wishSID'] = GetNewSurveyID($iDesiredSurveyId);
        }
        if ($iDBVersion <= 143) {
            if (isset($insertdata['private'])) {
                $insertdata['anonymized'] = $insertdata['private'];
            }
            unset($insertdata['private']);
            unset($insertdata['notification']);
        }
        unset($insertdata['expires']);
        unset($insertdata['startdate']);
        //Make sure it is not set active
        $insertdata['active'] = 'N';
        //Set current user to be the owner
        $insertdata['owner_id'] = Yii::app()->session['loginID'];
        if (isset($insertdata['bouncetime']) && $insertdata['bouncetime'] == '') {
            $insertdata['bouncetime'] = NULL;
        }
        if (isset($insertdata['showXquestions'])) {
            $insertdata['showxquestions'] = $insertdata['showXquestions'];
            unset($insertdata['showXquestions']);
        }
        $iNewSID = $results['newsid'] = Survey::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [1]<br />");
        $results['surveys']++;
    }
    // Import survey languagesettings table ===================================================================================
    foreach ($xml->surveys_languagesettings->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        if (!in_array($insertdata['surveyls_language'], $aLanguagesSupported)) {
            continue;
        }
        $insertdata['surveyls_survey_id'] = $iNewSID;
        if ($bTranslateInsertansTags) {
            if ($sNewSurveyName == NULL) {
                $insertdata['surveyls_title'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_title']);
            } else {
                $insertdata['surveyls_title'] = translateLinks('survey', $iOldSID, $iNewSID, $sNewSurveyName);
            }
            if (isset($insertdata['surveyls_description'])) {
                $insertdata['surveyls_description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_description']);
            }
            if (isset($insertdata['surveyls_welcometext'])) {
                $insertdata['surveyls_welcometext'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_welcometext']);
            }
            if (isset($insertdata['surveyls_urldescription'])) {
                $insertdata['surveyls_urldescription'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_urldescription']);
            }
            if (isset($insertdata['surveyls_email_invite'])) {
                $insertdata['surveyls_email_invite'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_invite']);
            }
            if (isset($insertdata['surveyls_email_remind'])) {
                $insertdata['surveyls_email_remind'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_remind']);
            }
            if (isset($insertdata['surveyls_email_register'])) {
                $insertdata['surveyls_email_register'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_register']);
            }
            if (isset($insertdata['surveyls_email_confirm'])) {
                $insertdata['surveyls_email_confirm'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_confirm']);
            }
        }
        $result = Surveys_languagesettings::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [2]<br />");
    }
    // Import groups table ===================================================================================
    if (isset($xml->groups->rows->row)) {
        foreach ($xml->groups->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported)) {
                continue;
            }
            $iOldSID = $insertdata['sid'];
            $insertdata['sid'] = $iNewSID;
            $oldgid = $insertdata['gid'];
            unset($insertdata['gid']);
            // save the old qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['group_name'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['group_name']);
                $insertdata['description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['description']);
            }
            // Insert the new group
            if (isset($aGIDReplacements[$oldgid])) {
                switchMSSQLIdentityInsert('groups', true);
                $insertdata['gid'] = $aGIDReplacements[$oldgid];
            }
            $newgid = Groups::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [3]<br />");
            $results['groups']++;
            if (!isset($aGIDReplacements[$oldgid])) {
                $aGIDReplacements[$oldgid] = $newgid;
                // add old and new qid to the mapping array
            } else {
                switchMSSQLIdentityInsert('groups', false);
            }
        }
    }
    // Import questions table ===================================================================================
    // We have to run the question table data two times - first to find all main questions
    // then for subquestions (because we need to determine the new qids for the main questions first)
    if (isset($xml->questions)) {
        foreach ($xml->questions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) {
                continue;
            }
            $iOldSID = $insertdata['sid'];
            $insertdata['sid'] = $iNewSID;
            $insertdata['gid'] = $aGIDReplacements[$insertdata['gid']];
            $oldqid = $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
                $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
            }
            // Insert the new question
            if (isset($aQIDReplacements[$oldqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldqid];
                switchMSSQLIdentityInsert('questions', true);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            $newqid = Questions::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [4]<br />");
            if (!isset($aQIDReplacements[$oldqid])) {
                $aQIDReplacements[$oldqid] = $newqid;
                $results['questions']++;
            } else {
                switchMSSQLIdentityInsert('questions', false);
            }
        }
    }
    // Import subquestions -------------------------------------------------------
    if (isset($xml->subquestions)) {
        foreach ($xml->subquestions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) {
                continue;
            }
            if (!isset($insertdata['mandatory']) || trim($insertdata['mandatory']) == '') {
                $insertdata['mandatory'] = 'N';
            }
            $insertdata['sid'] = $iNewSID;
            $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
            $oldsqid = (int) $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            $insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']];
            // remap the parent_qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
                if (isset($insertdata['help'])) {
                    $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
                }
            }
            if (isset($aQIDReplacements[$oldsqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldsqid];
                switchMSSQLIdentityInsert('questions', true);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            $newsqid = Questions::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [5]<br />");
            if (!isset($insertdata['qid'])) {
                $aQIDReplacements[$oldsqid] = $newsqid;
                // add old and new qid to the mapping array
            } else {
                switchMSSQLIdentityInsert('questions', false);
            }
            $results['subquestions']++;
        }
    }
    // Import answers ------------------------------------------------------------
    if (isset($xml->answers)) {
        foreach ($xml->answers->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || !isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the parent_qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['answer'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['answer']);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            $result = Answers::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['answers']++;
        }
    }
    // Import questionattributes -------------------------------------------------
    if (isset($xml->question_attributes)) {
        $aAllAttributes = questionAttributes(true);
        foreach ($xml->question_attributes->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            unset($insertdata['qaid']);
            if (!isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if ($iDBVersion < 148 && isset($aAllAttributes[$insertdata['attribute']]['i18n']) && $aAllAttributes[$insertdata['attribute']]['i18n']) {
                foreach ($aLanguagesSupported as $sLanguage) {
                    $insertdata['language'] = $sLanguage;
                    if ($insertdata) {
                        XSSFilterArray($insertdata);
                    }
                    $result = Question_attributes::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
                }
            } else {
                $result = Question_attributes::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            }
            $results['question_attributes']++;
        }
    }
    // Import defaultvalues ------------------------------------------------------
    if (isset($xml->defaultvalues)) {
        $results['defaultvalues'] = 0;
        foreach ($xml->defaultvalues->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if (isset($aQIDReplacements[(int) $insertdata['sqid']])) {
                $insertdata['sqid'] = $aQIDReplacements[(int) $insertdata['sqid']];
            }
            // remap the subquestion id
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            // now translate any links
            $result = Defaultvalues::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['defaultvalues']++;
        }
    }
    $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements);
    // Import conditions ---------------------------------------------------------
    if (isset($xml->conditions)) {
        $results['conditions'] = 0;
        foreach ($xml->conditions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$insertdata['qid']])) {
                $insertdata['qid'] = $aQIDReplacements[$insertdata['qid']];
                // remap the qid
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            if ($insertdata['cqid'] != 0) {
                if (isset($aQIDReplacements[$insertdata['cqid']])) {
                    $oldcqid = $insertdata['cqid'];
                    //Save for cfield transformation
                    $insertdata['cqid'] = $aQIDReplacements[$insertdata['cqid']];
                    // remap the qid
                } else {
                    continue;
                }
                // a problem with this answer record -> don't consider
                list($oldcsid, $oldcgid, $oldqidanscode) = explode("X", $insertdata["cfieldname"], 3);
                // replace the gid for the new one in the cfieldname(if there is no new gid in the $aGIDReplacements array it means that this condition is orphan -> error, skip this record)
                if (!isset($aGIDReplacements[$oldcgid])) {
                    continue;
                }
            }
            unset($insertdata["cid"]);
            // recreate the cfieldname with the new IDs
            if ($insertdata['cqid'] != 0) {
                if (preg_match("/^\\+/", $oldcsid)) {
                    $newcfieldname = '+' . $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid));
                } else {
                    $newcfieldname = $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid));
                }
            } else {
                // The cfieldname is a not a previous question cfield but a {XXXX} replacement field
                $newcfieldname = $insertdata["cfieldname"];
            }
            $insertdata["cfieldname"] = $newcfieldname;
            if (trim($insertdata["method"]) == '') {
                $insertdata["method"] = '==';
            }
            // Now process the value and replace @sgqa@ codes
            if (preg_match("/^@(.*)@\$/", $insertdata["value"], $cfieldnameInCondValue)) {
                if (isset($aOldNewFieldmap[$cfieldnameInCondValue[1]])) {
                    $newvalue = '@' . $aOldNewFieldmap[$cfieldnameInCondValue[1]] . '@';
                    $insertdata["value"] = $newvalue;
                }
            }
            // now translate any links
            $result = Conditions::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['conditions']++;
        }
    }
    // TMSW Conditions->Relevance:  Call  LEM->ConvertConditionsToRelevance
    // Import assessments --------------------------------------------------------
    if (isset($xml->assessments)) {
        foreach ($xml->assessments->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if ($insertdata['gid'] > 0) {
                $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
                // remap the qid
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            // now translate any links
            $result = Assessment::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['assessments']++;
        }
    }
    // Import quota --------------------------------------------------------------
    if (isset($xml->quota)) {
        foreach ($xml->quota->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $oldid = $insertdata['id'];
            unset($insertdata['id']);
            // now translate any links
            $result = Quota::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $aQuotaReplacements[$oldid] = Yii::app()->db->getCommandBuilder()->getLastInsertID('{{quota}}');
            $results['quota']++;
        }
    }
    // Import quota_members ------------------------------------------------------
    if (isset($xml->quota_members)) {
        foreach ($xml->quota_members->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            $insertdata['quota_id'] = $aQuotaReplacements[(int) $insertdata['quota_id']];
            // remap the qid
            unset($insertdata['id']);
            // now translate any links
            $result = Quota_members::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['quotamembers']++;
        }
    }
    // Import quota_languagesettings----------------------------------------------
    if (isset($xml->quota_languagesettings)) {
        foreach ($xml->quota_languagesettings->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['quotals_quota_id'] = $aQuotaReplacements[(int) $insertdata['quotals_quota_id']];
            // remap the qid
            unset($insertdata['quotals_id']);
            $result = Quota_languagesettings::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['quotals']++;
        }
    }
    // Import survey_url_parameters ----------------------------------------------
    if (isset($xml->survey_url_parameters)) {
        foreach ($xml->survey_url_parameters->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            if (isset($insertdata['targetsqid']) && $insertdata['targetsqid'] != '') {
                $insertdata['targetsqid'] = $aSQIDReplacements[(int) $insertdata['targetsqid']];
                // remap the qid
            }
            if (isset($insertdata['targetqid']) && $insertdata['targetqid'] != '') {
                $insertdata['targetqid'] = $aQIDReplacements[(int) $insertdata['targetqid']];
                // remap the qid
            }
            unset($insertdata['id']);
            $result = Survey_url_parameters::model()->insertRecord($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['survey_url_parameters']++;
        }
    }
    // Set survey rights
    Survey_permissions::model()->giveAllSurveyPermissions(Yii::app()->session['loginID'], $iNewSID);
    $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements);
    $results['FieldReMap'] = $aOldNewFieldmap;
    LimeExpressionManager::SetSurveyId($iNewSID);
    translateInsertansTags($iNewSID, $iOldSID, $aOldNewFieldmap);
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID);
    LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID);
    return $results;
}
Esempio n. 17
0
/**
* This function imports a LimeSurvey .lss survey XML file
*
* @param mixed $sFullFilePath  The full filepath of the uploaded file
*/
function XMLImportSurvey($sFullFilePath, $sXMLdata = NULL, $sNewSurveyName = NULL, $iDesiredSurveyId = NULL, $bTranslateInsertansTags = true, $bConvertInvalidQuestionCodes = true)
{
    Yii::app()->loadHelper('database');
    $clang = Yii::app()->lang;
    $aGIDReplacements = array();
    if ($sXMLdata == NULL) {
        $sXMLdata = file_get_contents($sFullFilePath);
    }
    $xml = @simplexml_load_string($sXMLdata, 'SimpleXMLElement', LIBXML_NONET);
    if (!$xml || $xml->LimeSurveyDocType != 'Survey') {
        $results['error'] = $clang->gT("This is not a valid LimeSurvey survey structure XML file.");
        return $results;
    }
    $pre_personal_characteristics = "";
    $question_groups['R'] = array();
    $question_groups['I'] = array();
    $question_groups['O'] = array();
    $iDBVersion = (int) $xml->DBVersion;
    $aQIDReplacements = array();
    $aQuestionCodeReplacements = array();
    $aQuotaReplacements = array();
    $results['defaultvalues'] = 0;
    $results['answers'] = 0;
    $results['surveys'] = 0;
    $results['questions'] = 0;
    $results['subquestions'] = 0;
    $results['question_attributes'] = 0;
    $results['groups'] = 0;
    $results['assessments'] = 0;
    $results['quota'] = 0;
    $results['quotals'] = 0;
    $results['quotamembers'] = 0;
    $results['survey_url_parameters'] = 0;
    $results['importwarnings'] = array();
    $aLanguagesSupported = array();
    foreach ($xml->languages->language as $language) {
        $aLanguagesSupported[] = (string) $language;
    }
    $results['languages'] = count($aLanguagesSupported);
    // Import surveys table ====================================================
    foreach ($xml->surveys->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        $iOldSID = $results['oldsid'] = $insertdata['sid'];
        if ($iDesiredSurveyId != NULL) {
            $insertdata['wishSID'] = GetNewSurveyID($iDesiredSurveyId);
        } else {
            $insertdata['wishSID'] = $iOldSID;
        }
        if ($iDBVersion < 145) {
            if (isset($insertdata['private'])) {
                $insertdata['anonymized'] = $insertdata['private'];
            }
            unset($insertdata['private']);
            unset($insertdata['notification']);
        }
        //Make sure it is not set active
        $insertdata['active'] = 'N';
        //Set current user to be the owner
        $insertdata['owner_id'] = Yii::app()->session['loginID'];
        if (isset($insertdata['bouncetime']) && $insertdata['bouncetime'] == '') {
            $insertdata['bouncetime'] = NULL;
        }
        if (isset($insertdata['showXquestions'])) {
            $insertdata['showxquestions'] = $insertdata['showXquestions'];
            unset($insertdata['showXquestions']);
        }
        // Special code to set javascript in
        Yii::app()->loadHelper('admin/template');
        $newname = "watson_" . time();
        $newdirname = Yii::app()->getConfig('usertemplaterootdir') . "/" . $newname;
        $copydirname = getTemplatePath("watson_personal_constructs_copy_me");
        $oFileHelper = new CFileHelper();
        $mkdirresult = mkdir_p($newdirname);
        if ($mkdirresult == 1) {
            $oFileHelper->copyDirectory($copydirname, $newdirname);
            $templatename = $newname;
            //$this->index("startpage.pstpl", "welcome", $templatename);
        } elseif ($mkdirresult == 2) {
            $results['Error'] = sprintf($clang->gT("Directory with the name `%s` already exists - choose another name", "js"), $newname);
        } else {
            $results['Error'] = sprintf($clang->gT("Unable to create directory `%s`.", "js"), $newname) . " " . $clang->gT("Please check the directory permissions.", "js");
        }
        $insertdata['template'] = $newname;
        // End special copy code (taken from templates.php templatecopy() method
        if (isset($insertdata['googleAnalyticsStyle'])) {
            $insertdata['googleanalyticsstyle'] = $insertdata['googleAnalyticsStyle'];
            unset($insertdata['googleAnalyticsStyle']);
        }
        if (isset($insertdata['googleAnalyticsAPIKey'])) {
            $insertdata['googleanalyticsapikey'] = $insertdata['googleAnalyticsAPIKey'];
            unset($insertdata['googleAnalyticsAPIKey']);
        }
        if (isset($insertdata['allowjumps'])) {
            $insertdata['questionindex'] = $insertdata['allowjumps'] == "Y" ? 1 : 0;
            unset($insertdata['allowjumps']);
        }
        /* Remove unknow column */
        $aSurveyModelsColumns = Survey::model()->attributes;
        $aSurveyModelsColumns['wishSID'] = null;
        // To force a sid surely
        $aBadData = array_diff_key($insertdata, $aSurveyModelsColumns);
        $insertdata = array_intersect_key($insertdata, $aSurveyModelsColumns);
        // Fill a optionnal array of error
        foreach ($aBadData as $key => $value) {
            $results['importwarnings'][] = sprintf($clang->gT("This survey setting has not been imported: %s => %s"), $key, $value);
        }
        $iNewSID = $results['newsid'] = Survey::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [1]<br />");
        $pre_personal_characteristics = file_get_contents($newdirname . "/question.pstpl");
        $results['surveys']++;
    }
    // Import survey languagesettings table ===================================================================================
    foreach ($xml->surveys_languagesettings->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        if (!in_array($insertdata['surveyls_language'], $aLanguagesSupported)) {
            continue;
        }
        // Assign new survey ID
        $insertdata['surveyls_survey_id'] = $iNewSID;
        // Assign new survey name (if a copy)
        if ($sNewSurveyName != NULL) {
            $insertdata['surveyls_title'] = $sNewSurveyName;
        }
        if ($bTranslateInsertansTags) {
            $insertdata['surveyls_title'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_title']);
            if (isset($insertdata['surveyls_description'])) {
                $insertdata['surveyls_description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_description']);
            }
            if (isset($insertdata['surveyls_welcometext'])) {
                $insertdata['surveyls_welcometext'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_welcometext']);
            }
            if (isset($insertdata['surveyls_urldescription'])) {
                $insertdata['surveyls_urldescription'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_urldescription']);
            }
            if (isset($insertdata['surveyls_email_invite'])) {
                $insertdata['surveyls_email_invite'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_invite']);
            }
            if (isset($insertdata['surveyls_email_remind'])) {
                $insertdata['surveyls_email_remind'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_remind']);
            }
            if (isset($insertdata['surveyls_email_register'])) {
                $insertdata['surveyls_email_register'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_register']);
            }
            if (isset($insertdata['surveyls_email_confirm'])) {
                $insertdata['surveyls_email_confirm'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_confirm']);
            }
        }
        if (isset($insertdata['surveyls_attributecaptions']) && substr($insertdata['surveyls_attributecaptions'], 0, 1) != '{') {
            unset($insertdata['surveyls_attributecaptions']);
        }
        $result = SurveyLanguageSetting::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [2]<br />");
    }
    // Import groups table ===================================================================================
    if (isset($xml->groups->rows->row)) {
        foreach ($xml->groups->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported)) {
                continue;
            }
            $iOldSID = $insertdata['sid'];
            $insertdata['sid'] = $iNewSID;
            $oldgid = $insertdata['gid'];
            unset($insertdata['gid']);
            // save the old qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['group_name'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['group_name']);
                $insertdata['description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['description']);
            }
            // Insert the new group
            if (isset($aGIDReplacements[$oldgid])) {
                switchMSSQLIdentityInsert('groups', true);
                $insertdata['gid'] = $aGIDReplacements[$oldgid];
            }
            $newgid = QuestionGroup::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [3]<br />");
            if ($insertdata['group_name'] == 'Real Characteristics' || $insertdata['group_name'] == 'PC - Real Characteristics') {
                $question_groups['R'][] = $newgid;
            } else {
                if ($insertdata['group_name'] == 'Ideal Characteristics' || $insertdata['group_name'] == 'PC - Ideal Characteristics') {
                    $question_groups['I'][] = $newgid;
                } else {
                    if ($insertdata['group_name'] == 'Ought Characteristics' || $insertdata['group_name'] == 'PC - Ought Characteristics') {
                        $question_groups['O'][] = $newgid;
                    }
                }
            }
            $results['groups']++;
            if (!isset($aGIDReplacements[$oldgid])) {
                $aGIDReplacements[$oldgid] = $newgid;
                // add old and new qid to the mapping array
            } else {
                switchMSSQLIdentityInsert('groups', false);
            }
        }
    }
    // Import questions table ===================================================================================
    // We have to run the question table data two times - first to find all main questions
    // then for subquestions (because we need to determine the new qids for the main questions first)
    if (isset($xml->questions)) {
        foreach ($xml->questions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) {
                continue;
            }
            $iOldSID = $insertdata['sid'];
            $insertdata['sid'] = $iNewSID;
            $insertdata['gid'] = $aGIDReplacements[$insertdata['gid']];
            $oldqid = $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
                $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
            }
            // Insert the new question
            if (isset($aQIDReplacements[$oldqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldqid];
                switchMSSQLIdentityInsert('questions', true);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            if (!$bConvertInvalidQuestionCodes) {
                $sScenario = 'archiveimport';
            } else {
                $sScenario = 'import';
            }
            $oQuestion = new Question($sScenario);
            $oQuestion->setAttributes($insertdata, false);
            // Try to fix question title for valid question code enforcement
            if (!$oQuestion->validate(array('title'))) {
                $sOldTitle = $oQuestion->title;
                $sNewTitle = preg_replace("/[^A-Za-z0-9]/", '', $sOldTitle);
                if (is_numeric(substr($sNewTitle, 0, 1))) {
                    $sNewTitle = 'q' . $sNewTitle;
                }
                $oQuestion->title = $sNewTitle;
            }
            $attempts = 0;
            // Try to fix question title for unique question code enforcement
            while (!$oQuestion->validate(array('title'))) {
                if (!isset($index)) {
                    $index = 0;
                    $rand = mt_rand(0, 1024);
                } else {
                    $index++;
                }
                $sNewTitle = 'r' . $rand . 'q' . $index;
                $oQuestion->title = $sNewTitle;
                $attempts++;
                if ($attempts > 10) {
                    safeDie($clang->gT("Error") . ": Failed to resolve question code problems after 10 attempts.<br />");
                }
            }
            if (!$oQuestion->save()) {
                // safeDie($clang->gT("Error while saving: "). print_r($oQuestion->errors, true));
                //
                // In PHP 5.2.10 a bug is triggered that resets the foreach loop when inserting a record
                // Problem is that it is the default PHP version on Ubuntu 12.04 LTS (which is currently very common in use)
                // For this reason we ignore insertion errors (because it is most likely a duplicate)
                // and continue with the next one
                continue;
            }
            // Set a warning if question title was updated
            if (isset($sNewTitle)) {
                $results['importwarnings'][] = sprintf($clang->gT("Question code %s was updated to %s."), $sOldTitle, $sNewTitle);
                $aQuestionCodeReplacements[$sOldTitle] = $sNewTitle;
                unset($sNewTitle);
                unset($sOldTitle);
            }
            $newqid = $oQuestion->qid;
            if (!isset($aQIDReplacements[$oldqid])) {
                $aQIDReplacements[$oldqid] = $newqid;
                $results['questions']++;
            } else {
                switchMSSQLIdentityInsert('questions', false);
            }
        }
    }
    // Import subquestions -------------------------------------------------------
    if (isset($xml->subquestions)) {
        foreach ($xml->subquestions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) {
                continue;
            }
            if (!isset($insertdata['mandatory']) || trim($insertdata['mandatory']) == '') {
                $insertdata['mandatory'] = 'N';
            }
            $insertdata['sid'] = $iNewSID;
            $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
            $oldsqid = (int) $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            $insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']];
            // remap the parent_qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
                if (isset($insertdata['help'])) {
                    $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
                }
            }
            if (isset($aQIDReplacements[$oldsqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldsqid];
                switchMSSQLIdentityInsert('questions', true);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            if (!$bConvertInvalidQuestionCodes) {
                $sScenario = 'archiveimport';
            } else {
                $sScenario = 'import';
            }
            $question = new Question($sScenario);
            $question->setAttributes($insertdata, false);
            // Try to fix question title for valid question code enforcement
            if (!$question->validate(array('title'))) {
                $sOldTitle = $question->title;
                $sNewTitle = preg_replace("/[^A-Za-z0-9]/", '', $sOldTitle);
                if (is_numeric(substr($sNewTitle, 0, 1))) {
                    $sNewTitle = 'sq' . $sNewTitle;
                }
                $question->title = $sNewTitle;
            }
            $attempts = 0;
            // Try to fix question title for unique question code enforcement
            while (!$question->validate(array('title'))) {
                if (!isset($index)) {
                    $index = 0;
                    $rand = mt_rand(0, 1024);
                } else {
                    $index++;
                }
                $sNewTitle = 'r' . $rand . 'sq' . $index;
                $question->title = $sNewTitle;
                $attempts++;
                if ($attempts > 10) {
                    safeDie($clang->gT("Error") . ": Failed to resolve question code problems after 10 attempts.<br />");
                }
            }
            if (!$question->save()) {
                // safeDie($clang->gT("Error while saving: "). print_r($question->errors, true));
                //
                // In PHP 5.2.10 a bug is triggered that resets the foreach loop when inserting a record
                // Problem is that it is the default PHP version on Ubuntu 12.04 LTS (which is currently very common in use)
                // For this reason we ignore insertion errors (because it is most likely a duplicate)
                // and continue with the next one
                continue;
            }
            // Set a warning if question title was updated
            if (isset($sNewTitle)) {
                $results['importwarnings'][] = sprintf($clang->gT("Title of subquestion %s was updated to %s."), $sOldTitle, $sNewTitle);
                // Maybe add the question title ?
                $aQuestionCodeReplacements[$sOldTitle] = $sNewTitle;
                unset($sNewTitle);
                unset($sOldTitle);
            }
            $newsqid = $question->qid;
            if (!isset($insertdata['qid'])) {
                $aQIDReplacements[$oldsqid] = $newsqid;
                // add old and new qid to the mapping array
            } else {
                switchMSSQLIdentityInsert('questions', false);
            }
            $results['subquestions']++;
        }
    }
    // Import answers ------------------------------------------------------------
    if (isset($xml->answers)) {
        foreach ($xml->answers->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || !isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the parent_qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['answer'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['answer']);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            if (Answer::model()->insertRecords($insertdata)) {
                $results['answers']++;
            }
        }
    }
    // Import questionattributes -------------------------------------------------
    if (isset($xml->question_attributes)) {
        $aAllAttributes = questionAttributes(true);
        foreach ($xml->question_attributes->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            // take care of renaming of date min/max adv. attributes fields
            if ($iDBVersion < 170) {
                if (isset($insertdata['attribute'])) {
                    if ($insertdata['attribute'] == 'dropdown_dates_year_max') {
                        $insertdata['attribute'] = 'date_max';
                    }
                    if ($insertdata['attribute'] == 'dropdown_dates_year_min') {
                        $insertdata['attribute'] = 'date_min';
                    }
                }
            }
            unset($insertdata['qaid']);
            if (!isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if ($iDBVersion < 156 && isset($aAllAttributes[$insertdata['attribute']]['i18n']) && $aAllAttributes[$insertdata['attribute']]['i18n']) {
                foreach ($aLanguagesSupported as $sLanguage) {
                    $insertdata['language'] = $sLanguage;
                    if ($insertdata) {
                        XSSFilterArray($insertdata);
                    }
                    $result = QuestionAttribute::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[7]<br />");
                }
            } else {
                $result = QuestionAttribute::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[8]<br />");
            }
            $results['question_attributes']++;
        }
    }
    // Import defaultvalues ------------------------------------------------------
    if (isset($xml->defaultvalues)) {
        $results['defaultvalues'] = 0;
        foreach ($xml->defaultvalues->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if (isset($aQIDReplacements[(int) $insertdata['sqid']])) {
                $insertdata['sqid'] = $aQIDReplacements[(int) $insertdata['sqid']];
            }
            // remap the subquestion id
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            // now translate any links
            $result = DefaultValue::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[9]<br />");
            $results['defaultvalues']++;
        }
    }
    $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements);
    // Import conditions ---------------------------------------------------------
    if (isset($xml->conditions)) {
        $results['conditions'] = 0;
        foreach ($xml->conditions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$insertdata['qid']])) {
                $insertdata['qid'] = $aQIDReplacements[$insertdata['qid']];
                // remap the qid
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            if ($insertdata['cqid'] != 0) {
                if (isset($aQIDReplacements[$insertdata['cqid']])) {
                    $oldcqid = $insertdata['cqid'];
                    //Save for cfield transformation
                    $insertdata['cqid'] = $aQIDReplacements[$insertdata['cqid']];
                    // remap the qid
                } else {
                    continue;
                }
                // a problem with this answer record -> don't consider
                list($oldcsid, $oldcgid, $oldqidanscode) = explode("X", $insertdata["cfieldname"], 3);
                // replace the gid for the new one in the cfieldname(if there is no new gid in the $aGIDReplacements array it means that this condition is orphan -> error, skip this record)
                if (!isset($aGIDReplacements[$oldcgid])) {
                    continue;
                }
            }
            unset($insertdata["cid"]);
            // recreate the cfieldname with the new IDs
            if ($insertdata['cqid'] != 0) {
                if (preg_match("/^\\+/", $oldcsid)) {
                    $newcfieldname = '+' . $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid));
                } else {
                    $newcfieldname = $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid));
                }
            } else {
                // The cfieldname is a not a previous question cfield but a {XXXX} replacement field
                $newcfieldname = $insertdata["cfieldname"];
            }
            $insertdata["cfieldname"] = $newcfieldname;
            if (trim($insertdata["method"]) == '') {
                $insertdata["method"] = '==';
            }
            // Now process the value and replace @sgqa@ codes
            if (preg_match("/^@(.*)@\$/", $insertdata["value"], $cfieldnameInCondValue)) {
                if (isset($aOldNewFieldmap[$cfieldnameInCondValue[1]])) {
                    $newvalue = '@' . $aOldNewFieldmap[$cfieldnameInCondValue[1]] . '@';
                    $insertdata["value"] = $newvalue;
                }
            }
            // now translate any links
            $result = Condition::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[10]<br />");
            $results['conditions']++;
        }
    }
    // TMSW Condition->Relevance:  Call  LEM->ConvertConditionsToRelevance
    // Import assessments --------------------------------------------------------
    if (isset($xml->assessments)) {
        foreach ($xml->assessments->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if ($insertdata['gid'] > 0) {
                $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
                // remap the qid
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            unset($insertdata['id']);
            // now translate any links
            $result = Assessment::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[11]<br />");
            $results['assessments']++;
        }
    }
    // Import quota --------------------------------------------------------------
    if (isset($xml->quota)) {
        foreach ($xml->quota->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $oldid = $insertdata['id'];
            unset($insertdata['id']);
            // now translate any links
            $result = Quota::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[12]<br />");
            $aQuotaReplacements[$oldid] = getLastInsertID('{{quota}}');
            $results['quota']++;
        }
    }
    // Import quota_members ------------------------------------------------------
    if (isset($xml->quota_members)) {
        foreach ($xml->quota_members->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            $insertdata['quota_id'] = $aQuotaReplacements[(int) $insertdata['quota_id']];
            // remap the qid
            unset($insertdata['id']);
            // now translate any links
            $result = QuotaMember::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[13]<br />");
            $results['quotamembers']++;
        }
    }
    // Import quota_languagesettings----------------------------------------------
    if (isset($xml->quota_languagesettings)) {
        foreach ($xml->quota_languagesettings->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['quotals_quota_id'] = $aQuotaReplacements[(int) $insertdata['quotals_quota_id']];
            // remap the qid
            unset($insertdata['quotals_id']);
            $result = QuotaLanguageSetting::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['quotals']++;
        }
    }
    // Import survey_url_parameters ----------------------------------------------
    if (isset($xml->survey_url_parameters)) {
        foreach ($xml->survey_url_parameters->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            if (isset($insertdata['targetsqid']) && $insertdata['targetsqid'] != '') {
                $insertdata['targetsqid'] = $aQIDReplacements[(int) $insertdata['targetsqid']];
                // remap the qid
            }
            if (isset($insertdata['targetqid']) && $insertdata['targetqid'] != '') {
                $insertdata['targetqid'] = $aQIDReplacements[(int) $insertdata['targetqid']];
                // remap the qid
            }
            unset($insertdata['id']);
            $result = SurveyURLParameter::model()->insertRecord($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[14]<br />");
            $results['survey_url_parameters']++;
        }
    }
    // Set survey rights
    Permission::model()->giveAllSurveyPermissions(Yii::app()->session['loginID'], $iNewSID);
    $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements);
    $results['FieldReMap'] = $aOldNewFieldmap;
    LimeExpressionManager::SetSurveyId($iNewSID);
    translateInsertansTags($iNewSID, $iOldSID, $aOldNewFieldmap);
    replaceExpressionCodes($iNewSID, $aQuestionCodeReplacements);
    if (count($aQuestionCodeReplacements)) {
        array_unshift($results['importwarnings'], "<span class='warningtitle'>" . $clang->gT('Attention: Several question codes were updated. Please check these carefully as the update  may not be perfect with customized expressions.') . '</span)>');
    }
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID);
    LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID);
    $js_variables = array();
    if (!empty($question_groups['R'])) {
        $real_count = 1;
        $ideal_count = 1;
        $ought_count = 1;
        foreach ($results['FieldReMap'] as $code) {
            $value = explode('X', $code);
            if (isset($value[1]) && in_array($value[1], $question_groups['R'])) {
                if (!array_key_exists((int) $value[1], $js_variables)) {
                    $int = substr($value[2], 0, strpos($value[2], 'PC'));
                    $js_variables[$value[1]] = "var realGroupId" . $real_count . " = " . $value[1] . ";";
                    $js_variables[$value[1] . "-q"] = "var realQuestionId" . $real_count . " = " . $int . ";";
                    $real_count++;
                }
            } else {
                if (isset($value[1]) && in_array($value[1], $question_groups['I'])) {
                    if (!array_key_exists((int) $value[1], $js_variables)) {
                        $int = substr($value[2], 0, strpos($value[2], 'PC'));
                        $js_variables[$value[1]] = "var idealGroupId" . $ideal_count . " = " . $value[1] . ";";
                        $js_variables[$value[1] . "-q"] = "var idealQuestionId" . $ideal_count . " = " . $int . ";";
                        $ideal_count++;
                    }
                } else {
                    if (isset($value[1]) && in_array($value[1], $question_groups['O'])) {
                        if (!array_key_exists((int) $value[1], $js_variables)) {
                            $int = substr($value[2], 0, strpos($value[2], 'PC'));
                            $js_variables[$value[1]] = "var oughtGroupId" . $ought_count . " = " . $value[1] . ";";
                            $js_variables[$value[1] . "-q"] = "var oughtQuestionId" . $ought_count . " = " . $int . ";";
                            $ought_count++;
                        }
                    }
                }
            }
        }
        $js_variables[] = "var surveyId = " . $value[0] . ";";
    }
    if (!empty($js_variables)) {
        $pre_personal_characteristics = str_replace("[REPLACE_ME]", implode(PHP_EOL, $js_variables), $pre_personal_characteristics);
    } else {
        $pre_personal_characteristics = '<div {QUESTION_ESSENTIALS} class="{QUESTION_CLASS}{QUESTION_MAN_CLASS}{QUESTION_INPUT_ERROR_CLASS}">
          <div class="survey-question">
            <div class="survey-question-text">
                  <span class="asterisk">{QUESTION_MANDATORY}</span><span class="qnumcode"> {QUESTION_NUMBER} {QUESTION_CODE} </span>{QUESTION_TEXT}<br /><span class="questionhelp">{QUESTION_HELP}</span>
              {QUESTION_MAN_MESSAGE}
              {QUESTION_VALID_MESSAGE}
              {QUESTION_FILE_VALID_MESSAGE}
            </div>
            <div class="survey-question-answer">{ANSWER}</div>
            <div class="survey-question-help">{QUESTIONHELP}</div>
          </div>
          <div class="survey-question-space"></div>
        </div>';
    }
    file_put_contents($newdirname . "/question.pstpl", $pre_personal_characteristics);
    return $results;
}
 public function postCompileBilling()
 {
     $eid = Session::get('eid');
     $pid = Session::get('pid');
     $practice_id = Session::get('practice_id');
     $row = Demographics::find($pid);
     $encounterInfo = Encounters::find($eid);
     $dos1 = $this->human_to_unix($encounterInfo->encounter_DOS);
     $dos = date('mdY', $dos1);
     $dos2 = date('m/d/Y', $dos1);
     $pos = $encounterInfo->encounter_location;
     $assessment_data = Assessment::find($eid);
     $icd_pointer = '';
     if ($assessment_data->assessment_1 != '') {
         $icd_pointer .= "A";
     }
     if ($assessment_data->assessment_2 != '') {
         $icd_pointer .= "B";
     }
     if ($assessment_data->assessment_3 != '') {
         $icd_pointer .= "C";
     }
     if ($assessment_data->assessment_4 != '') {
         $icd_pointer .= "D";
     }
     $labsInfo = Labs::find($eid);
     if ($labsInfo) {
         if ($labsInfo->labs_ua_urobili != '' || $labsInfo->labs_ua_bilirubin != '' || $labsInfo->labs_ua_ketones != '' || $labsInfo->labs_ua_glucose != '' || $labsInfo->labs_ua_protein != '' || $labsInfo->labs_ua_nitrites != '' || $labsInfo->labs_ua_leukocytes != '' || $labsInfo->labs_ua_blood != '' || $labsInfo->labs_ua_ph != '' || $labsInfo->labs_ua_spgr != '' || $labsInfo->labs_ua_color != '' || $labsInfo->labs_ua_clarity != '') {
             $this->compile_procedure_billing('81002', $eid, $pid, $dos2, $icd_pointer, $practice_id);
         }
         if ($labsInfo->labs_upt != '') {
             $this->compile_procedure_billing('81025', $eid, $pid, $dos2, $icd_pointer, $practice_id);
         }
         if ($labsInfo->labs_strep != '') {
             $this->compile_procedure_billing('87880', $eid, $pid, $dos2, $icd_pointer, $practice_id);
         }
         if ($labsInfo->labs_mono != '') {
             $this->compile_procedure_billing('86308', $eid, $pid, $dos2, $icd_pointer, $practice_id);
         }
         if ($labsInfo->labs_flu != '') {
             $this->compile_procedure_billing('87804', $eid, $pid, $dos2, $icd_pointer, $practice_id);
         }
         if ($labsInfo->labs_glucose != '') {
             $this->compile_procedure_billing('82962', $eid, $pid, $dos2, $icd_pointer, $practice_id);
         }
     }
     $result9 = Procedure::find($eid);
     if ($result9) {
         $this->compile_procedure_billing($result9->proc_cpt, $eid, $pid, $dos2, $icd_pointer, $practice_id);
     }
     $result11 = Immunizations::where('eid', '=', $eid)->get();
     if ($result11) {
         foreach ($result11 as $row11) {
             $this->compile_procedure_billing($row11->cpt, $eid, $pid, $dos2, $icd_pointer, $practice_id);
         }
     }
     echo 'CPT codes complied from the encounter!';
 }
 public function postGetBilling($eid = '')
 {
     if ($eid == '') {
         $eid = Session::get('eid');
     }
     $data = Assessment::find($eid);
     if ($data) {
         $data1['message'] = "OK";
         if ($data->assessment_1 != '') {
             $data1['A'] = "A - " . $data->assessment_1;
         } else {
             $data1['message'] = "No diagnoses available.";
         }
         if ($data->assessment_2 != '') {
             $data1['B'] = "B - " . $data->assessment_2;
         }
         if ($data->assessment_3 != '') {
             $data1['C'] = "C - " . $data->assessment_3;
         }
         if ($data->assessment_4 != '') {
             $data1['D'] = "D - " . $data->assessment_4;
         }
         if ($data->assessment_5 != '') {
             $data1['E'] = "E - " . $data->assessment_5;
         }
         if ($data->assessment_6 != '') {
             $data1['F'] = "F - " . $data->assessment_6;
         }
         if ($data->assessment_7 != '') {
             $data1['G'] = "G - " . $data->assessment_7;
         }
         if ($data->assessment_8 != '') {
             $data1['H'] = "H - " . $data->assessment_8;
         }
         if ($data->assessment_9 != '') {
             $data1['I'] = "I - " . $data->assessment_9;
         }
         if ($data->assessment_10 != '') {
             $data1['J'] = "J - " . $data->assessment_10;
         }
         if ($data->assessment_11 != '') {
             $data1['K'] = "K - " . $data->assessment_11;
         }
         if ($data->assessment_12 != '') {
             $data1['L'] = "L - " . $data->assessment_12;
         }
     } else {
         $data1['message'] = "No diagnoses available.";
     }
     echo json_encode($data1);
 }
Esempio n. 20
0
 protected function page_invoice1($eid)
 {
     $pid = Session::get('pid');
     $assessmentInfo = Assessment::find($eid);
     if ($assessmentInfo) {
         $data['assessment'] = '';
         if ($assessmentInfo->assessment_1 != '') {
             $data['assessment'] .= $assessmentInfo->assessment_1 . '<br />';
             if ($assessmentInfo->assessment_2 == '') {
                 $data['assessment'] .= '<br />';
             }
         }
         if ($assessmentInfo->assessment_2 != '') {
             $data['assessment'] .= $assessmentInfo->assessment_2 . '<br />';
             if ($assessmentInfo->assessment_3 == '') {
                 $data['assessment'] .= '<br />';
             }
         }
         if ($assessmentInfo->assessment_3 != '') {
             $data['assessment'] .= $assessmentInfo->assessment_3 . '<br />';
             if ($assessmentInfo->assessment_4 == '') {
                 $data['assessment'] .= '<br />';
             }
         }
         if ($assessmentInfo->assessment_4 != '') {
             $data['assessment'] .= $assessmentInfo->assessment_4 . '<br />';
             if ($assessmentInfo->assessment_5 == '') {
                 $data['assessment'] .= '<br />';
             }
         }
         if ($assessmentInfo->assessment_5 != '') {
             $data['assessment'] .= $assessmentInfo->assessment_5 . '<br />';
             if ($assessmentInfo->assessment_6 == '') {
                 $data['assessment'] .= '<br />';
             }
         }
         if ($assessmentInfo->assessment_6 != '') {
             $data['assessment'] .= $assessmentInfo->assessment_6 . '<br />';
             if ($assessmentInfo->assessment_7 == '') {
                 $data['assessment'] .= '<br />';
             }
         }
         if ($assessmentInfo->assessment_7 != '') {
             $data['assessment'] .= $assessmentInfo->assessment_7 . '<br />';
             if ($assessmentInfo->assessment_8 == '') {
                 $data['assessment'] .= '<br />';
             }
         }
         if ($assessmentInfo->assessment_8 != '') {
             $data['assessment'] .= $assessmentInfo->assessment_8 . '<br /><br />';
         }
     } else {
         $data['assessment'] = '';
     }
     $result1 = DB::table('billing_core')->where('eid', '=', $eid)->orderBy('cpt_charge', 'desc')->get();
     if ($result1) {
         $charge = 0;
         $payment = 0;
         $data['text'] = '<table class="pure-table"><tr><th style="width:14%">PROCEDURE</th><th style="width:14%">UNITS</th><th style="width:50%">DESCRIPTION</th><th style="width:22%">CHARGE PER UNIT</th></tr>';
         foreach ($result1 as $key1 => $value1) {
             $cpt_charge1[$key1] = $value1->cpt_charge;
         }
         array_multisort($cpt_charge1, SORT_DESC, $result1);
         foreach ($result1 as $result1a) {
             if ($result1a->cpt) {
                 $query2 = DB::table('cpt_relate')->where('cpt', '=', $result1a->cpt)->first();
                 if ($query2) {
                     $result2 = DB::table('cpt_relate')->where('cpt', '=', $result1a->cpt)->first();
                 } else {
                     $result2 = DB::table('cpt')->where('cpt', '=', $result1a->cpt)->first();
                 }
                 $data['text'] .= '<tr><td>' . $result1a->cpt . '</td><td>' . $result1a->unit . '</td><td>' . $result2->cpt_description . '</td><td>$' . $result1a->cpt_charge . '</td></tr>';
                 $charge += $result1a->cpt_charge * $result1a->unit;
             } else {
                 $data['text'] .= '<tr><td>Date of Payment:</td><td>' . $result1a->dos_f . '</td><td>' . $result1a->payment_type . '</td><td">$(' . $result1a->payment . ')</td></tr>';
                 $payment = $payment + $result1a->payment;
             }
         }
         $balance = $charge - $payment;
         $charge = number_format($charge, 2, '.', ',');
         $payment = number_format($payment, 2, '.', ',');
         $balance = number_format($balance, 2, '.', ',');
         $data['text'] .= '<tr><td></td><td></td><td><strong>Total Charges:</strong></td><td><strong>$' . $charge . '</strong></td></tr><tr><td></td><td></td><td><strong>Total Payments:</strong></td><td><strong>$' . $payment . '</strong></td></tr><tr><td></td><td></td><td></td><td><hr/></td></tr><tr><td></td><td></td><td><strong>Remaining Balance:</strong></td><td><strong>$' . $balance . '</strong></td></tr></table>';
     } else {
         $data['text'] = 'No procedures.';
     }
     $row = Demographics::find($pid);
     $practice = Practiceinfo::find(Session::get('practice_id'));
     $data['practiceName'] = $practice->practice_name;
     $data['practiceInfo1'] = $practice->street_address1;
     if ($practice->street_address2 != '') {
         $data['practiceInfo1'] .= ', ' . $practice->street_address2;
     }
     $data['practiceInfo2'] = $practice->city . ', ' . $practice->state . ' ' . $practice->zip;
     $data['practiceInfo3'] = 'Phone: ' . $practice->phone . ', Fax: ' . $practice->fax;
     $data['disclaimer'] = '<br>Please send a check payable to ' . $practice->practice_name . ' and mail it to:';
     $data['disclaimer'] .= '<br>' . $practice->billing_street_address1;
     if ($practice->billing_street_address2 != '') {
         $data['text'] .= ', ' . $practice->billing_street_address2;
     }
     $data['disclaimer'] .= '<br>' . $practice->billing_city . ', ' . $practice->billing_state . ' ' . $practice->billing_zip;
     $data['patientInfo1'] = $row->firstname . ' ' . $row->lastname;
     $data['patientInfo2'] = $row->address;
     $data['patientInfo3'] = $row->city . ', ' . $row->state . ' ' . $row->zip;
     $data['patientInfo'] = $row;
     $data['dob'] = date('m/d/Y', $this->human_to_unix($row->DOB));
     $encounterInfo = Encounters::find($eid);
     $data['encounter_DOS'] = date('F jS, Y', $this->human_to_unix($encounterInfo->encounter_DOS));
     $data['encounter_provider'] = $encounterInfo->encounter_provider;
     $query1 = DB::table('insurance')->where('pid', '=', $pid)->where('insurance_plan_active', '=', 'Yes')->get();
     $data['insuranceInfo'] = '';
     if ($query1) {
         foreach ($query1 as $row1) {
             $data['insuranceInfo'] .= $row1->insurance_plan_name . '; ID: ' . $row1->insurance_id_num . '; Group: ' . $row1->insurance_group . '; ' . $row1->insurance_insu_lastname . ', ' . $row1->insurance_insu_firstname . '<br><br>';
         }
     }
     $data['title'] = "INVOICE";
     $data['date'] = date('F jS, Y', time());
     $result = DB::table('demographics_notes')->where('pid', '=', Session::get('pid'))->where('practice_id', '=', Session::get('practice_id'))->first();
     if (is_null($result->billing_notes) || $result->billing_notes == '') {
         $billing_notes = 'Invoice for encounter (Date of Service: ' . $data['encounter_DOS'] . ') printed on ' . $data['date'] . '.';
     } else {
         $billing_notes = $result->billing_notes . "\n" . 'Invoice for encounter (Date of Service: ' . $data['encounter_DOS'] . ') printed on ' . $data['date'] . '.';
     }
     $billing_notes_data = array('billing_notes' => $billing_notes);
     DB::table('demographics_notes')->where('pid', '=', Session::get('pid'))->where('practice_id', '=', Session::get('practice_id'))->update($billing_notes_data);
     $this->audit('Update');
     return View::make('pdf.invoice_page', $data);
 }
Esempio n. 21
0
 public function getLetter(\DOMElement $context)
 {
     return Assessment::LETTER($this->score);
 }
 /**
  * Deletes a survey and all its data
  *
  * @access public
  * @param int $iSurveyID
  * @param bool @recursive
  * @return void
  */
 public function deleteSurvey($iSurveyID, $recursive = true)
 {
     Survey::model()->deleteByPk($iSurveyID);
     if ($recursive == true) {
         if (tableExists("{{survey_" . intval($iSurveyID) . "}}")) {
             Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "}}");
         }
         if (tableExists("{{survey_" . intval($iSurveyID) . "_timings}}")) {
             Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "_timings}}");
         }
         if (tableExists("{{tokens_" . intval($iSurveyID) . "}}")) {
             Yii::app()->db->createCommand()->dropTable("{{tokens_" . intval($iSurveyID) . "}}");
         }
         $oResult = Question::model()->findAllByAttributes(array('sid' => $iSurveyID));
         foreach ($oResult as $aRow) {
             Answer::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Condition::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             QuestionAttribute::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             DefaultValue::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
         }
         Question::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Assessment::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         QuestionGroup::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         SurveyLanguageSetting::model()->deleteAllByAttributes(array('surveyls_survey_id' => $iSurveyID));
         Permission::model()->deleteAllByAttributes(array('entity_id' => $iSurveyID, 'entity' => 'survey'));
         SavedControl::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         SurveyURLParameter::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         //Remove any survey_links to the CPDB
         SurveyLink::model()->deleteLinksBySurvey($iSurveyID);
         Quota::model()->deleteQuota(array('sid' => $iSurveyID), true);
     }
 }
Esempio n. 23
0
 /**
  * This function checks the LimeSurvey database for logical consistency and returns an according array
  * containing all issues in the particular tables.
  * @returns Array with all found issues.
  */
 protected function _checkintegrity()
 {
     $clang = Yii::app()->lang;
     /*** Plainly delete survey permissions if the survey or user does not exist ***/
     $users = User::model()->findAll();
     $uids = array();
     foreach ($users as $user) {
         $uids[] = $user['uid'];
     }
     $oCriteria = new CDbCriteria();
     $oCriteria->addNotInCondition('uid', $uids, 'OR');
     $surveys = Survey::model()->findAll();
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $oCriteria->addNotInCondition('entity_id', $sids, 'OR');
     $oCriteria->addCondition("entity='survey'");
     Permission::model()->deleteAll($oCriteria);
     // Deactivate surveys that have a missing response table
     foreach ($surveys as $survey) {
         if ($survey['active'] == 'Y' && !tableExists("{{survey_{$survey['sid']}}}")) {
             Survey::model()->updateByPk($survey['sid'], array('active' => 'N'));
         }
     }
     unset($surveys);
     // Fix subquestions
     fixSubquestions();
     /*** Check for active survey tables with missing survey entry and rename them ***/
     $sDBPrefix = Yii::app()->db->tablePrefix;
     $sQuery = dbSelectTablesLike('{{survey}}\\_%');
     $aResult = dbQueryOrFalse($sQuery);
     foreach ($aResult->readAll() as $aRow) {
         $sTableName = substr(reset($aRow), strlen($sDBPrefix));
         if ($sTableName == 'survey_links' || $sTableName == 'survey_url_parameters') {
             continue;
         }
         $aTableName = explode('_', $sTableName);
         if (isset($aTableName[1]) && ctype_digit($aTableName[1])) {
             $iSurveyID = $aTableName[1];
             if (!in_array($iSurveyID, $sids)) {
                 $sDate = date('YmdHis') . rand(1, 1000);
                 $sOldTable = "survey_{$iSurveyID}";
                 $sNewTable = "old_survey_{$iSurveyID}_{$sDate}";
                 try {
                     $deactivateresult = Yii::app()->db->createCommand()->renameTable("{{{$sOldTable}}}", "{{{$sNewTable}}}");
                 } catch (CDbException $e) {
                     die('Couldn\'t make backup of the survey table. Please try again. The database reported the following error:<br />' . htmlspecialchars($e) . '<br />');
                 }
             }
         }
     }
     /*** Check for active token tables with missing survey entry ***/
     $aResult = dbQueryOrFalse(dbSelectTablesLike('{{tokens}}\\_%'));
     foreach ($aResult->readAll() as $aRow) {
         $sTableName = substr(reset($aRow), strlen($sDBPrefix));
         $iSurveyID = substr($sTableName, strpos($sTableName, '_') + 1);
         if (!in_array($iSurveyID, $sids)) {
             $sDate = date('YmdHis') . rand(1, 1000);
             $sOldTable = "tokens_{$iSurveyID}";
             $sNewTable = "old_tokens_{$iSurveyID}_{$sDate}";
             try {
                 $deactivateresult = Yii::app()->db->createCommand()->renameTable("{{{$sOldTable}}}", "{{{$sNewTable}}}");
             } catch (CDbException $e) {
                 die('Couldn\'t make backup of the survey table. Please try again. The database reported the following error:<br />' . htmlspecialchars($e) . '<br />');
             }
         }
     }
     /**********************************************************************/
     /*     Check conditions                                               */
     /**********************************************************************/
     $okQuestion = array();
     $sQuery = 'SELECT cqid,cid,cfieldname FROM {{conditions}}';
     $aConditions = Yii::app()->db->createCommand($sQuery)->queryAll();
     foreach ($aConditions as $condition) {
         if ($condition['cqid'] != 0) {
             // skip case with cqid=0 for codnitions on {TOKEN:EMAIL} for instance
             if (!array_key_exists($condition['cqid'], $okQuestion)) {
                 $iRowCount = Question::model()->countByAttributes(array('qid' => $condition['cqid']));
                 if (Question::model()->hasErrors()) {
                     safeDie(Question::model()->getError());
                 }
                 if (!$iRowCount) {
                     $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No matching CQID'));
                 } else {
                     $okQuestion[$condition['cqid']] = $condition['cqid'];
                 }
             }
         }
         if ($condition['cfieldname']) {
             if (preg_match('/^\\+{0,1}[0-9]+X[0-9]+X*$/', $condition['cfieldname'])) {
                 // only if cfieldname isn't Tag such as {TOKEN:EMAIL} or any other token
                 list($surveyid, $gid, $rest) = explode('X', $condition['cfieldname']);
                 $iRowCount = count(QuestionGroup::model()->findAllByAttributes(array('gid' => $gid)));
                 if (QuestionGroup::model()->hasErrors()) {
                     safeDie(QuestionGroup::model()->getError());
                 }
                 if (!$iRowCount) {
                     $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No matching CFIELDNAME group!') . " ({$gid}) ({$condition['cfieldname']})");
                 }
             }
         } elseif (!$condition['cfieldname']) {
             $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No CFIELDNAME field set!') . " ({$condition['cfieldname']})");
         }
     }
     unset($okQuestion);
     unset($aConditions);
     /**********************************************************************/
     /*     Check question attributes                                      */
     /**********************************************************************/
     $question_attributes = QuestionAttribute::model()->findAllBySql('select qid from {{question_attributes}} where qid not in (select qid from {{questions}})');
     if (QuestionAttribute::model()->hasErrors()) {
         safeDie(QuestionAttribute::model()->getError());
     }
     foreach ($question_attributes as $question_attribute) {
         $aDelete['questionattributes'][] = array('qid' => $question_attribute['qid']);
     }
     // foreach
     /**********************************************************************/
     /*     Check default values                                           */
     /**********************************************************************/
     $oCriteria = new CDbCriteria();
     $oCriteria->join = 'LEFT JOIN {{questions}} q ON t.qid=q.qid';
     $oCriteria->condition = 'q.qid IS NULL';
     $aRecords = DefaultValue::model()->findAll($oCriteria);
     $aDelete['defaultvalues'] = count($aRecords);
     if (DefaultValue::model()->hasErrors()) {
         safeDie(DefaultValue::model()->getError());
     }
     /**********************************************************************/
     /*     Check quotas                                                   */
     /**********************************************************************/
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $oCriteria = new CDbCriteria();
     $oCriteria->addNotInCondition('sid', $sids);
     $aDelete['quotas'] = count(Quota::model()->findAll($oCriteria));
     if (Quota::model()->hasErrors()) {
         safeDie(Quota::model()->getError());
     }
     /**********************************************************************/
     /*     Check quota languagesettings                                   */
     /**********************************************************************/
     $quotas = Quota::model()->findAll();
     if (Quota::model()->hasErrors()) {
         safeDie(Quota::model()->getError());
     }
     $ids = array();
     foreach ($quotas as $quota) {
         $ids[] = $quota['id'];
     }
     $oCriteria = new CDbCriteria();
     $oCriteria->addNotInCondition('quotals_quota_id', $ids);
     $aDelete['quotals'] = count(QuotaLanguageSetting::model()->findAll($oCriteria));
     if (QuotaLanguageSetting::model()->hasErrors()) {
         safeDie(QuotaLanguageSetting::model()->getError());
     }
     /**********************************************************************/
     /*     Check quota members                                   */
     /**********************************************************************/
     $oCriteria = new CDbCriteria();
     $oCriteria->join = 'LEFT JOIN {{questions}} q ON t.qid=q.qid LEFT JOIN {{surveys}} s ON t.sid=s.sid';
     $oCriteria->condition = '(q.qid IS NULL) OR (s.sid IS NULL)';
     $aDelete['quotamembers'] = count(QuotaMember::model()->findAll($oCriteria));
     if (QuotaMember::model()->hasErrors()) {
         safeDie(QuotaMember::model()->getError());
     }
     /**********************************************************************/
     /*     Check assessments                                              */
     /**********************************************************************/
     $oCriteria = new CDbCriteria();
     $oCriteria->compare('scope', 'T');
     $assessments = Assessment::model()->findAll($oCriteria);
     if (Assessment::model()->hasErrors()) {
         safeDie(Assessment::model()->getError());
     }
     foreach ($assessments as $assessment) {
         $iAssessmentCount = count(Survey::model()->findAllByPk($assessment['sid']));
         if (Survey::model()->hasErrors()) {
             safeDie(Survey::model()->getError());
         }
         if (!$iAssessmentCount) {
             $aDelete['assessments'][] = array('id' => $assessment['id'], 'assessment' => $assessment['name'], 'reason' => $clang->gT('No matching survey'));
         }
     }
     $oCriteria = new CDbCriteria();
     $oCriteria->compare('scope', 'G');
     $assessments = Assessment::model()->findAll($oCriteria);
     if (Assessment::model()->hasErrors()) {
         safeDie(Assessment::model()->getError());
     }
     foreach ($assessments as $assessment) {
         $iAssessmentCount = count(QuestionGroup::model()->findAllByPk(array('gid' => $assessment['gid'], 'language' => $assessment['language'])));
         if (QuestionGroup::model()->hasErrors()) {
             safeDie(QuestionGroup::model()->getError());
         }
         if (!$iAssessmentCount) {
             $aDelete['assessments'][] = array('id' => $assessment['id'], 'assessment' => $assessment['name'], 'reason' => $clang->gT('No matching group'));
         }
     }
     unset($assessments);
     /**********************************************************************/
     /*     Check answers                                                  */
     /**********************************************************************/
     $oCriteria = new CDbCriteria();
     $oCriteria->join = 'LEFT JOIN {{questions}} q ON t.qid=q.qid';
     $oCriteria->condition = '(q.qid IS NULL)';
     $answers = Answer::model()->findAll($oCriteria);
     foreach ($answers as $answer) {
         $aDelete['answers'][] = array('qid' => $answer['qid'], 'code' => $answer['code'], 'reason' => $clang->gT('No matching question'));
     }
     /***************************************************************************/
     /*   Check survey languagesettings and restore them if they don't exist    */
     /***************************************************************************/
     $surveys = Survey::model()->findAll();
     foreach ($surveys as $survey) {
         $aLanguages = $survey->additionalLanguages;
         $aLanguages[] = $survey->language;
         foreach ($aLanguages as $langname) {
             if ($langname) {
                 $oLanguageSettings = SurveyLanguageSetting::model()->find('surveyls_survey_id=:surveyid AND surveyls_language=:langname', array(':surveyid' => $survey->sid, ':langname' => $langname));
                 if (!$oLanguageSettings) {
                     $oLanguageSettings = new SurveyLanguageSetting();
                     $languagedetails = getLanguageDetails($langname);
                     $insertdata = array('surveyls_survey_id' => $survey->sid, 'surveyls_language' => $langname, 'surveyls_title' => '', 'surveyls_dateformat' => $languagedetails['dateformat']);
                     foreach ($insertdata as $k => $v) {
                         $oLanguageSettings->{$k} = $v;
                     }
                     $usresult = $oLanguageSettings->save();
                 }
             }
         }
     }
     /**********************************************************************/
     /*     Check survey language settings                                 */
     /**********************************************************************/
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $oCriteria = new CDbCriteria();
     $oCriteria->addNotInCondition('surveyls_survey_id', $sids);
     $surveys_languagesettings = SurveyLanguageSetting::model()->findAll($oCriteria);
     if (SurveyLanguageSetting::model()->hasErrors()) {
         safeDie(SurveyLanguageSetting::model()->getError());
     }
     foreach ($surveys_languagesettings as $surveys_languagesetting) {
         $aDelete['surveylanguagesettings'][] = array('slid' => $surveys_languagesetting['surveyls_survey_id'], 'reason' => $clang->gT('The related survey is missing.'));
     }
     /**********************************************************************/
     /*     Check questions                                                */
     /**********************************************************************/
     $oCriteria = new CDbCriteria();
     $oCriteria->join = 'LEFT JOIN {{surveys}} s ON t.sid=s.sid LEFT JOIN {{groups}} g ON t.gid=g.gid';
     $oCriteria->condition = '(g.gid IS NULL) OR (s.sid IS NULL)';
     $questions = Question::model()->findAll($oCriteria);
     if (Question::model()->hasErrors()) {
         safeDie(Question::model()->getError());
     }
     foreach ($questions as $question) {
         $aDelete['questions'][] = array('qid' => $question['qid'], 'reason' => $clang->gT('No matching group') . " ({$question['gid']})");
     }
     /**********************************************************************/
     /*     Check groups                                                   */
     /**********************************************************************/
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $oCriteria = new CDbCriteria();
     $oCriteria->addNotInCondition('sid', $sids);
     $groups = QuestionGroup::model()->findAll($oCriteria);
     foreach ($groups as $group) {
         $aDelete['groups'][] = array('gid' => $group['gid'], 'reason' => $clang->gT('There is no matching survey.') . ' SID:' . $group['sid']);
     }
     /**********************************************************************/
     /*     Check old survey tables                                        */
     /**********************************************************************/
     //1: Get list of 'old_survey' tables and extract the survey id
     //2: Check if that survey id still exists
     //3: If it doesn't offer it for deletion
     $sQuery = dbSelectTablesLike('{{old_survey}}%');
     $aTables = Yii::app()->db->createCommand($sQuery)->queryColumn();
     $aOldSIDs = array();
     $aSIDs = array();
     foreach ($aTables as $sTable) {
         list($sOldText, $SurveyText, $iSurveyID, $sDate) = explode('_', substr($sTable, strlen($sDBPrefix)));
         $aOldSIDs[] = $iSurveyID;
         $aFullOldSIDs[$iSurveyID][] = $sTable;
     }
     $aOldSIDs = array_unique($aOldSIDs);
     //$sQuery = 'SELECT sid FROM {{surveys}} ORDER BY sid';
     //$oResult = dbExecuteAssoc($sQuery) or safeDie('Couldn\'t get unique survey ids');
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $aSIDs = array();
     foreach ($surveys as $survey) {
         $aSIDs[] = $survey['sid'];
     }
     foreach ($aOldSIDs as $iOldSID) {
         if (!in_array($iOldSID, $aSIDs)) {
             foreach ($aFullOldSIDs[$iOldSID] as $sTableName) {
                 $aDelete['orphansurveytables'][] = $sTableName;
             }
         } else {
             foreach ($aFullOldSIDs[$iOldSID] as $sTableName) {
                 $aTableParts = explode('_', substr($sTableName, strlen($sDBPrefix)));
                 if (count($aTableParts) == 4) {
                     $sOldText = $aTableParts[0];
                     $SurveyText = $aTableParts[1];
                     $iSurveyID = $aTableParts[2];
                     $sDateTime = $aTableParts[3];
                     $sType = $clang->gT('responses');
                 } elseif (count($aTableParts) == 5) {
                     //This is a timings table (
                     $sOldText = $aTableParts[0];
                     $SurveyText = $aTableParts[1];
                     $iSurveyID = $aTableParts[2];
                     $sDateTime = $aTableParts[4];
                     $sType = $clang->gT('timings');
                 }
                 $iYear = substr($sDateTime, 0, 4);
                 $iMonth = substr($sDateTime, 4, 2);
                 $iDay = substr($sDateTime, 6, 2);
                 $iHour = substr($sDateTime, 8, 2);
                 $iMinute = substr($sDateTime, 10, 2);
                 $sDate = date('d M Y  H:i', mktime($iHour, $iMinute, 0, $iMonth, $iDay, $iYear));
                 $sQuery = 'SELECT count(*) as recordcount FROM ' . $sTableName;
                 $aFirstRow = Yii::app()->db->createCommand($sQuery)->queryRow();
                 if ($aFirstRow['recordcount'] == 0) {
                     // empty table - so add it to immediate deletion
                     $aDelete['orphansurveytables'][] = $sTableName;
                 } else {
                     $aOldSurveyTableAsk[] = array('table' => $sTableName, 'details' => sprintf($clang->gT('Survey ID %d saved at %s containing %d record(s) (%s)'), $iSurveyID, $sDate, $aFirstRow['recordcount'], $sType));
                 }
             }
         }
     }
     /**********************************************************************/
     /*     CHECK OLD TOKEN  TABLES                                        */
     /**********************************************************************/
     //1: Get list of 'old_token' tables and extract the survey id
     //2: Check if that survey id still exists
     //3: If it doesn't offer it for deletion
     $sQuery = dbSelectTablesLike('{{old_token}}%');
     $aTables = Yii::app()->db->createCommand($sQuery)->queryColumn();
     $aOldTokenSIDs = array();
     $aTokenSIDs = array();
     $aFullOldTokenSIDs = array();
     foreach ($aTables as $sTable) {
         list($sOldText, $SurveyText, $iSurveyID, $sDateTime) = explode('_', substr($sTable, strlen($sDBPrefix)));
         $aTokenSIDs[] = $iSurveyID;
         $aFullOldTokenSIDs[$iSurveyID][] = $sTable;
     }
     $aOldTokenSIDs = array_unique($aTokenSIDs);
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $aSIDs = array();
     foreach ($surveys as $survey) {
         $aSIDs[] = $survey['sid'];
     }
     foreach ($aOldTokenSIDs as $iOldTokenSID) {
         if (!in_array($iOldTokenSID, $aOldTokenSIDs)) {
             foreach ($aFullOldTokenSIDs[$iOldTokenSID] as $sTableName) {
                 $aDelete['orphantokentables'][] = $sTableName;
             }
         } else {
             foreach ($aFullOldTokenSIDs[$iOldTokenSID] as $sTableName) {
                 list($sOldText, $sTokensText, $iSurveyID, $sDateTime) = explode('_', substr($sTableName, strlen($sDBPrefix)));
                 $iYear = substr($sDateTime, 0, 4);
                 $iMonth = substr($sDateTime, 4, 2);
                 $iDay = substr($sDateTime, 6, 2);
                 $iHour = substr($sDateTime, 8, 2);
                 $iMinute = substr($sDateTime, 10, 2);
                 $sDate = date('D, d M Y  h:i a', mktime($iHour, $iMinute, 0, $iMonth, $iDay, $iYear));
                 $sQuery = 'SELECT count(*) as recordcount FROM ' . $sTableName;
                 $aFirstRow = Yii::app()->db->createCommand($sQuery)->queryRow();
                 if ($aFirstRow['recordcount'] == 0) {
                     // empty table - so add it to immediate deletion
                     $aDelete['orphantokentables'][] = $sTableName;
                 } else {
                     $aOldTokenTableAsk[] = array('table' => $sTableName, 'details' => sprintf($clang->gT('Survey ID %d saved at %s containing %d record(s)'), $iSurveyID, $sDate, $aFirstRow['recordcount']));
                 }
             }
         }
     }
     if ($aDelete['defaultvalues'] == 0 && $aDelete['quotamembers'] == 0 && $aDelete['quotas'] == 0 && $aDelete['quotals'] == 0 && count($aDelete) == 4) {
         $aDelete['integrityok'] = true;
     } else {
         $aDelete['integrityok'] = false;
     }
     if (!isset($aOldTokenTableAsk) && !isset($aOldSurveyTableAsk)) {
         $aDelete['redundancyok'] = true;
     } else {
         $aDelete['redundancyok'] = false;
         $aDelete['redundanttokentables'] = array();
         $aDelete['redundantsurveytables'] = array();
         if (isset($aOldTokenTableAsk)) {
             $aDelete['redundanttokentables'] = $aOldTokenTableAsk;
         }
         if (isset($aOldSurveyTableAsk)) {
             $aDelete['redundantsurveytables'] = $aOldSurveyTableAsk;
         }
     }
     /**********************************************************************/
     /*     CHECK CPDB SURVEY_LINKS TABLE FOR REDUNDENT TOKEN TABLES       */
     /**********************************************************************/
     //1: Get distinct list of survey_link survey ids, check if tokens
     //   table still exists for each one, and remove if not
     /* TODO */
     /**********************************************************************/
     /*     CHECK CPDB SURVEY_LINKS TABLE FOR REDUNDENT TOKEN ENTRIES      */
     /**********************************************************************/
     //1: For each survey_link, see if the matching entry still exists in
     //   the token table and remove if it doesn't.
     /* TODO */
     return $aDelete;
 }
<?php

require_once "inc/initialize.php";
include "inc/header.php";
include 'inc/validate.php';
$my_date = date("Y-m-d");
$my_year = date("Y");
$reassessment_id = $_GET["reassessment_id"];
$team_id = $_GET['team_id'];
$user_id = $_GET['user_id'];
$goals_id = $_POST['goals_id'];
$reassessment = assessment::find_by_id($reassessment_id);
$team = team::find_by_id($team_id);
$user = user::find_by_id($user_id);
$goal = goal::find_by_id($goals_id);
$assessment = new Assessment();
$assessment->user_id = $_GET['user_id'];
$assessment->create_date = $my_date;
$assessment->assessment_period = $my_year;
$assessment->goals_id = $_POST['goals_id'];
$assessment->team_id = $team_id;
$assessment->course = filter_var($_POST['course'], FILTER_SANITIZE_SPECIAL_CHARS);
$assessment->outcome_assessment = filter_var($_POST['outcome_assessment'], FILTER_SANITIZE_SPECIAL_CHARS);
$assessment->performance_targets = filter_var($_POST['performance_targets'], FILTER_SANITIZE_SPECIAL_CHARS);
if ($team->team_type == 1) {
    $assessment->expected_outcome = filter_var($_POST['expected_outcome'], FILTER_SANITIZE_SPECIAL_CHARS);
} else {
    $assessment->slo_id = $reassessment->slo_id;
    //$assessment->course =$reassessment->course;
    $slo_id = $reassessment->slo_id;
    $slo = slo::find_by_id($slo_id);
    foreach ($assessmentlangs as $assessmentlang) {
        $position = 0;
        echo '<li class="ui-state-default ui-corner-top" style="clear: none;"><a href="#tablang' . $assessmentlang . '">' . getLanguageNameFromCode($assessmentlang, false);
        if ($assessmentlang == $baselang) {
            echo ' (' . $clang->gT("Base language") . ')';
        }
        echo '</a></li>';
    }
    ?>
    </ul>
    <?php 
    foreach ($assessmentlangs as $assessmentlang) {
        $heading = '';
        $message = '';
        if ($action == "assessmentedit") {
            $results = Assessment::model()->findAllByAttributes(array('id' => $_POST['id'], 'language' => $assessmentlang));
            foreach ($results as $row) {
                $editdata = $row->attributes;
            }
            $heading = htmlspecialchars($editdata['name'], ENT_QUOTES);
            $message = htmlspecialchars($editdata['message']);
        }
        ?>
	    <div id="tablang<?php 
        echo $assessmentlang;
        ?>
">
	    <ul><li><label for='name_<?php 
        echo $assessmentlang;
        ?>
'><?php 
 public static function deleteWithDependency($groupId, $surveyId)
 {
     // Abort if the survey is active
     $surveyIsActive = Survey::model()->findByPk($surveyId)->active !== 'N';
     if ($surveyIsActive) {
         Yii::app()->user->setFlash('error', gt("Can't delete question group when the survey is active"));
         return null;
     }
     $questionIds = QuestionGroup::getQuestionIdsInGroup($groupId);
     Question::deleteAllById($questionIds);
     Assessment::model()->deleteAllByAttributes(array('sid' => $surveyId, 'gid' => $groupId));
     return QuestionGroup::model()->deleteAllByAttributes(array('sid' => $surveyId, 'gid' => $groupId));
 }
 public function postTimeline()
 {
     $pid = Session::get('pid');
     $json = array();
     $date_arr = array();
     $query0 = DB::table('encounters')->where('pid', '=', $pid)->where('addendum', '=', 'n')->get();
     if ($query0) {
         foreach ($query0 as $row0) {
             $description = '';
             $procedureInfo = Procedure::find($row0->eid);
             if ($procedureInfo) {
                 $description .= '<br><h4>Procedures:</h4><p class="view">';
                 if ($procedureInfo->proc_type != '') {
                     $description .= '<strong>Procedure: </strong>';
                     $description .= nl2br($procedureInfo->proc_type);
                     $description .= '<br /><br />';
                 }
                 $description .= '</p>';
             }
             $assessmentInfo = Assessment::find($row0->eid);
             if ($assessmentInfo) {
                 $description .= '<br><h4>Assessment:</h4><p class="view">';
                 if ($assessmentInfo->assessment_1 != '') {
                     $description .= '<strong>' . $assessmentInfo->assessment_1 . '</strong><br />';
                     if ($assessmentInfo->assessment_2 == '') {
                         $description .= '<br />';
                     }
                 }
                 if ($assessmentInfo->assessment_2 != '') {
                     $description .= '<strong>' . $assessmentInfo->assessment_2 . '</strong><br />';
                     if ($assessmentInfo->assessment_3 == '') {
                         $description .= '<br />';
                     }
                 }
                 if ($assessmentInfo->assessment_3 != '') {
                     $description .= '<strong>' . $assessmentInfo->assessment_3 . '</strong><br />';
                     if ($assessmentInfo->assessment_4 == '') {
                         $description .= '<br />';
                     }
                 }
                 if ($assessmentInfo->assessment_4 != '') {
                     $description .= '<strong>' . $assessmentInfo->assessment_4 . '</strong><br />';
                     if ($assessmentInfo->assessment_5 == '') {
                         $description .= '<br />';
                     }
                 }
                 if ($assessmentInfo->assessment_5 != '') {
                     $description .= '<strong>' . $assessmentInfo->assessment_5 . '</strong><br />';
                     if ($assessmentInfo->assessment_6 == '') {
                         $description .= '<br />';
                     }
                 }
                 if ($assessmentInfo->assessment_6 != '') {
                     $description .= '<strong>' . $assessmentInfo->assessment_6 . '</strong><br />';
                     if ($assessmentInfo->assessment_7 == '') {
                         $description .= '<br />';
                     }
                 }
                 if ($assessmentInfo->assessment_7 != '') {
                     $description .= '<strong>' . $assessmentInfo->assessment_7 . '</strong><br />';
                     if ($assessmentInfo->assessment_8 == '') {
                         $description .= '<br />';
                     }
                 }
                 if ($assessmentInfo->assessment_8 != '') {
                     $description .= '<strong>' . $assessmentInfo->assessment_8 . '</strong><br /><br />';
                 }
                 if ($assessmentInfo->assessment_other != '') {
                     if ($row0->encounter_template == 'standardmtm') {
                         $description .= '<strong>SOAP Note: </strong>';
                     } else {
                         $description .= '<strong>Additional Diagnoses: </strong>';
                     }
                     $description .= nl2br($assessmentInfo->assessment_other);
                     $description .= '<br /><br />';
                 }
                 if ($assessmentInfo->assessment_ddx != '') {
                     if ($row0->encounter_template == 'standardmtm') {
                         $description .= '<strong>MAP2: </strong>';
                     } else {
                         $description .= '<strong>Differential Diagnoses Considered: </strong>';
                     }
                     $description .= nl2br($assessmentInfo->assessment_ddx);
                     $description .= '<br /><br />';
                 }
                 if ($assessmentInfo->assessment_notes != '') {
                     if ($row0->encounter_template == 'standardmtm') {
                         $description .= '<strong>Pharmacist Note: </strong>';
                     } else {
                         $description .= '<strong>Assessment Discussion: </strong>';
                     }
                     $description .= nl2br($assessmentInfo->assessment_notes);
                     $description .= '<br /><br />';
                 }
                 $description .= '</p>';
             }
             $json[] = array('title' => "<span class='timeline_event' value='" . $row0->eid . "' type='eid' status='" . $row0->encounter_signed . "'>Encounter: " . $row0->encounter_cc . "</span>", 'description' => $description, 'startDate' => $this->human_to_unix($row0->encounter_DOS));
             $date_arr[] = $this->human_to_unix($row0->encounter_DOS);
         }
     }
     $query1 = DB::table('t_messages')->where('pid', '=', $pid)->get();
     if ($query1) {
         foreach ($query1 as $row1) {
             $json[] = array('title' => "<span class='timeline_event' value='" . $row1->t_messages_id . "' type='t_messages_id' status='" . $row1->t_messages_signed . "'>Message: " . $row1->t_messages_subject . "</span>", 'description' => substr($row1->t_messages_message, 0, 500) . '...', 'startDate' => $this->human_to_unix($row1->t_messages_dos));
             $date_arr[] = $this->human_to_unix($row1->t_messages_dos);
         }
     }
     $query2 = DB::table('rx_list')->where('pid', '=', $pid)->orderBy('rxl_date_active', 'asc')->groupBy('rxl_medication')->get();
     if ($query2) {
         foreach ($query2 as $row2) {
             $row2a = DB::table('rx_list')->where('rxl_id', '=', $row2->rxl_id)->first();
             if ($row2->rxl_sig == '') {
                 $instructions = $row2->rxl_instructions;
             } else {
                 $instructions = $row2->rxl_sig . ' ' . $row2->rxl_route . ' ' . $row2->rxl_frequency;
             }
             $description2 = $row2->rxl_medication . ' ' . $row2->rxl_dosage . ' ' . $row2->rxl_dosage_unit . ', ' . $instructions . ' for ' . $row2->rxl_reason;
             $json[] = array('title' => "<span class='timeline_event' value='" . $row2->rxl_id . "' type='rxl_id'>New Medication Started</span>", 'description' => $description2, 'startDate' => $this->human_to_unix($row2->rxl_date_active));
             $date_arr[] = $this->human_to_unix($row2->rxl_date_active);
         }
     }
     $query3 = DB::table('issues')->where('pid', '=', $pid)->get();
     if ($query3) {
         foreach ($query3 as $row3) {
             if ($row3->type == 'Problem List') {
                 $title = 'New Problem';
             }
             if ($row3->type == 'Medical History') {
                 $title = 'New Medical Event';
             }
             if ($row3->type == 'Problem List') {
                 $title = 'New Surgical Event';
             }
             $json[] = array('title' => "<span class='timeline_event' value='" . $row3->issue_id . "' type='issue_id'>" . $title . "</span>", 'description' => $row3->issue, 'startDate' => $this->human_to_unix($row3->issue_date_active));
             $date_arr[] = $this->human_to_unix($row3->issue_date_active);
         }
     }
     $query4 = DB::table('immunizations')->where('pid', '=', $pid)->get();
     if ($query4) {
         foreach ($query4 as $row4) {
             $json[] = array('title' => "<span class='timeline_event' value='" . $row4->imm_id . "' type='imm_id'>Immunization Given</span>", 'description' => $row4->imm_immunization, 'startDate' => $this->human_to_unix($row4->imm_date));
             $date_arr[] = $this->human_to_unix($row4->imm_date);
         }
     }
     $query5 = DB::table('rx_list')->where('pid', '=', $pid)->where('rxl_date_inactive', '!=', '0000-00-00 00:00:00')->get();
     if ($query5) {
         foreach ($query5 as $row5) {
             $row5a = DB::table('rx_list')->where('rxl_id', '=', $row5->rxl_id)->first();
             if ($row5->rxl_sig == '') {
                 $instructions5 = $row5->rxl_instructions;
             } else {
                 $instructions5 = $row5->rxl_sig . ' ' . $row5->rxl_route . ' ' . $row5->rxl_frequency;
             }
             $description5 = $row5->rxl_medication . ' ' . $row5->rxl_dosage . ' ' . $row5->rxl_dosage_unit . ', ' . $instructions5 . ' for ' . $row5->rxl_reason;
             $json[] = array('title' => "<span class='timeline_event' value='" . $row5->rxl_id . "' type='rxl_id'>Medication Stopped</span>", 'description' => $description5, 'startDate' => $this->human_to_unix($row5->rxl_date_inactive));
             $date_arr[] = $this->human_to_unix($row5->rxl_date_inactive);
         }
     }
     $query6 = DB::table('allergies')->where('pid', '=', $pid)->where('allergies_date_inactive', '=', '0000-00-00 00:00:00')->get();
     if ($query6) {
         foreach ($query6 as $row6) {
             $json[] = array('title' => "<span class='timeline_event' value='" . $row6->allergies_id . "' type='allergies_id'>New Allergy</span>", 'description' => $row6->allergies_med, 'startDate' => $this->human_to_unix($row6->allergies_date_active));
             $date_arr[] = $this->human_to_unix($row6->allergies_date_active);
         }
     }
     foreach ($json as $key => $value) {
         $item[$key] = $value['startDate'];
     }
     array_multisort($item, SORT_ASC, $json);
     asort($date_arr);
     $arr['start'] = reset($date_arr);
     $arr['end'] = end($date_arr);
     if ($arr['end'] - $arr['start'] >= 315569260) {
         $arr['granular'] = 'decade';
     }
     if ($arr['end'] - $arr['start'] > 31556926 && $arr['end'] - $arr['start'] < 315569260) {
         $arr['granular'] = 'year';
     }
     if ($arr['end'] - $arr['start'] <= 31556926) {
         $arr['granular'] = 'month';
     }
     $arr['json'] = $json;
     echo json_encode($arr);
 }
Esempio n. 28
0
 /**
  * Deletes a survey and all its data
  *
  * @access public
  * @param int $iSurveyID
  * @param bool @recursive
  * @return void
  */
 public function deleteSurvey($iSurveyID, $recursive = true)
 {
     Survey::model()->deleteByPk($iSurveyID);
     if ($recursive == true) {
         if (tableExists("{{survey_" . intval($iSurveyID) . "}}")) {
             Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "}}");
         }
         if (tableExists("{{survey_" . intval($iSurveyID) . "_timings}}")) {
             Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "_timings}}");
         }
         if (tableExists("{{tokens_" . intval($iSurveyID) . "}}")) {
             Yii::app()->db->createCommand()->dropTable("{{tokens_" . intval($iSurveyID) . "}}");
         }
         /* Remove User/global settings part : need Question and QuestionGroup*/
         // Settings specific for this survey
         $oCriteria = new CDbCriteria();
         $oCriteria->compare('stg_name', 'last_%', true, 'AND', false);
         $oCriteria->compare('stg_value', $iSurveyID, false, 'AND');
         SettingGlobal::model()->deleteAll($oCriteria);
         // Settings specific for this survey, 2nd part
         $oCriteria = new CDbCriteria();
         $oCriteria->compare('stg_name', 'last_%' . $iSurveyID . '%', true, 'AND', false);
         SettingGlobal::model()->deleteAll($oCriteria);
         // All Group id from this survey for ALL users
         $aGroupId = CHtml::listData(QuestionGroup::model()->findAll(array('select' => 'gid', 'condition' => 'sid=:sid', 'params' => array(':sid' => $iSurveyID))), 'gid', 'gid');
         $oCriteria = new CDbCriteria();
         $oCriteria->compare('stg_name', 'last_question_gid_%', true, 'AND', false);
         if (Yii::app()->db->getDriverName() == 'pgsql') {
             $oCriteria->addInCondition('CAST(stg_value as ' . App()->db->schema->getColumnType("integer") . ')', $aGroupId);
         } else {
             $oCriteria->addInCondition('stg_value', $aGroupId);
         }
         SettingGlobal::model()->deleteAll($oCriteria);
         // All Question id from this survey for ALL users
         $aQuestionId = CHtml::listData(Question::model()->findAll(array('select' => 'qid', 'condition' => 'sid=:sid', 'params' => array(':sid' => $iSurveyID))), 'qid', 'qid');
         $oCriteria = new CDbCriteria();
         $oCriteria->compare('stg_name', 'last_question_%', true, 'OR', false);
         if (Yii::app()->db->getDriverName() == 'pgsql') {
             $oCriteria->addInCondition('CAST(stg_value as ' . App()->db->schema->getColumnType("integer") . ')', $aQuestionId);
         } else {
             $oCriteria->addInCondition('stg_value', $aQuestionId);
         }
         SettingGlobal::model()->deleteAll($oCriteria);
         $oResult = Question::model()->findAllByAttributes(array('sid' => $iSurveyID));
         foreach ($oResult as $aRow) {
             Answer::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Condition::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             QuestionAttribute::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             DefaultValue::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
         }
         Question::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Assessment::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         QuestionGroup::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         SurveyLanguageSetting::model()->deleteAllByAttributes(array('surveyls_survey_id' => $iSurveyID));
         Permission::model()->deleteAllByAttributes(array('entity_id' => $iSurveyID, 'entity' => 'survey'));
         SavedControl::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         SurveyURLParameter::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         //Remove any survey_links to the CPDB
         SurveyLink::model()->deleteLinksBySurvey($iSurveyID);
         Quota::model()->deleteQuota(array('sid' => $iSurveyID), true);
     }
 }
Esempio n. 29
0
 public static function deleteWithDependency($groupId, $surveyId)
 {
     $questionIds = Groups::getQuestionIdsInGroup($groupId);
     Questions::deleteAllById($questionIds);
     Assessment::model()->deleteAllByAttributes(array('sid' => $surveyId, 'gid' => $groupId));
     return Groups::model()->deleteAllByAttributes(array('sid' => $surveyId, 'gid' => $groupId));
 }
<?php

require_once "inc/initialize.php";
include 'inc/validate.php';
//Capture Assessment ID from url variable id
$assessment_id = $_GET["id"];
$assessment = new Assessment();
echo $assessment->delete('assessment_id', $assessment_id);
?>

      <html>
  <head>
    <title>IU Webmaster redirect</title>
    <META http-equiv="refresh" content="0;URL=sysadmin_report.php?admin=1">
  </head>
  <body bgcolor="#ffffff">

  </body>
</html>