add() public static method

public static add ( $target, $action, $data = null, $log_message = null, $properties = [] )
 /**
  * Lists local authorities from Commissioning Body Service
  *
  * @throws CHttpException
  */
 public function actionList()
 {
     \Audit::add('admin-CommissioningBodyService', 'list');
     if (!($commissioning_bt = \CommissioningBodyType::model()->findByAttributes(array('shortname' => 'LA')))) {
         throw new \CHttpException(500, 'Local Authority Commissioning Body Type is not configured.');
     }
     $service_type = \CommissioningBodyServiceType::model()->findByAttributes(array('shortname' => 'SSD'));
     $data['title'] = 'CVI Social Services Depts.';
     $data['commissioning_bt'] = $commissioning_bt;
     $data['service_type'] = $service_type;
     $data['return_url'] = '/OphCoCvi/localAuthoritiesAdmin/list';
     $data['base_data_url'] = 'OphCoCvi/localAuthoritiesAdmin/';
     $this->render('//admin/commissioning_body_services', $data);
 }
Ejemplo n.º 2
0
 public function actionManualAdd()
 {
     $worklist = new Worklist();
     if (!empty($_POST)) {
         $worklist->attributes = $_POST['Worklist'];
         if ($this->manager->createWorklistForUser($worklist)) {
             Audit::add('Manual-Worklist', 'add', $worklist->id);
             $this->redirect('/worklist/manual');
         } else {
             $errors = $worklist->getErrors();
         }
     }
     $this->render('//worklist/manual/add', array('worklist' => $worklist, 'errors' => @$errors));
 }
Ejemplo n.º 3
0
 public function actionEditTreatmentDrug($id)
 {
     if (!($model = OphTrIntravitrealinjection_Treatment_Drug::model()->findByPk((int) $id))) {
         throw new Exception('Treatment drug not found with id ' . $id);
     }
     if (isset($_POST['OphTrIntravitrealinjection_Treatment_Drug'])) {
         $model->attributes = $_POST['OphTrIntravitrealinjection_Treatment_Drug'];
         if ($model->save()) {
             Audit::add('admin', 'update', $model->id, null, array('module' => 'OphTrIntravitrealinjection', 'model' => 'OphTrIntravitrealinjection_Treatment_Drug'));
             Yii::app()->user->setFlash('success', 'Treatment drug updated');
             $this->redirect(array('ViewTreatmentDrugs'));
         }
     }
     $this->render('update', array('model' => $model, 'title' => 'Treatment Drug', 'cancel_uri' => '/OphTrIntravitrealinjection/admin/viewTreatmentDrugs'));
 }
Ejemplo n.º 4
0
 /**
  * Generate a list of current tickets.
  */
 public function actionIndex()
 {
     unset(Yii::app()->session['patientticket_ticket_in_review']);
     AutoSaveTicket::clear();
     $cat_id = Yii::app()->request->getParam('cat_id', null);
     $queueset_id = Yii::app()->request->getParam('queueset_id', null);
     $select_queue_set = Yii::app()->request->getParam('select_queue_set', null);
     if (!$cat_id) {
         throw new \CHttpException(404, 'Category ID required');
     }
     if ($qs_id = $queueset_id && $select_queue_set) {
         $this->redirect(array("/PatientTicketing/default/?queueset_id={$qs_id}&cat_id=" . $cat_id));
     }
     if ($queueset_id) {
         $qs_id = $queueset_id;
     }
     $qsc_svc = Yii::app()->service->getService(self::$QUEUESETCATEGORY_SERVICE);
     if (!($category = $qsc_svc->readActive((int) $cat_id))) {
         throw new \CHttpException(404, 'Invalid category id');
     }
     $queueset = null;
     $tickets = null;
     $pages = null;
     $patient_filter = null;
     if ($queuesets = $qsc_svc->getCategoryQueueSetsForUser($category, Yii::app()->user->id)) {
         // default to the single queueset if that is all that is available to the user
         if (count($queuesets) > 1) {
             if ($qs_id) {
                 foreach ($queuesets as $qs) {
                     if ($qs->getID() == $qs_id) {
                         $queueset = $qs;
                         break;
                     }
                 }
             }
         } else {
             $queueset = $queuesets[0];
         }
         if ($queueset) {
             // build the filter
             $filter_keys = array('queue-ids', 'priority-ids', 'subspecialty-id', 'firm-id', 'my-tickets', 'closed-tickets');
             $filter_options = array();
             if (empty($_POST)) {
                 if (($filter_options = Yii::app()->session['patientticket_filter']) && @$filter_options['category-id'] == $category->getID()) {
                     foreach ($filter_options as $k => $v) {
                         $_POST[$k] = $v;
                     }
                 }
             } else {
                 foreach ($filter_keys as $k) {
                     if (isset($_POST[$k])) {
                         $filter_options[$k] = $_POST[$k];
                     }
                 }
                 $filter_options['category-id'] = $category->getID();
             }
             Yii::app()->session['patientticket_filter'] = $filter_options;
             list($criteria, $patient_filter) = $this->buildTicketFilterCriteria($filter_options, $queueset);
             $count = models\Ticket::model()->count($criteria);
             $pages = new \CPagination($count);
             $pages->pageSize = $this->page_size;
             $pages->applyLimit($criteria);
             // get tickets that match criteria
             $tickets = models\Ticket::model()->findAll($criteria);
             \Audit::add('queueset', 'view', $queueset->getId());
         }
     }
     // render
     $this->render('index', array('category' => $category, 'queueset' => $queueset, 'tickets' => $tickets, 'patient_filter' => $patient_filter, 'pages' => $pages, 'cat_id' => $cat_id));
 }
 public function actionDelete()
 {
     if (isset($_POST['patientMergeRequestIds'])) {
         $criteria = new CDbCriteria();
         $criteria->condition = 't.status = ' . PatientMergeRequest::STATUS_NOT_PROCESSED;
         $requests = PatientMergeRequest::model()->findAllByPk($_POST['patientMergeRequestIds'], $criteria);
         foreach ($requests as $request) {
             $request->deleted = 1;
             if ($request->save()) {
                 Audit::add('Patient Merge', 'Patient Merge Request flagged as deleted. id: ' . $request->id);
             } else {
                 throw new Exception('Unable to save Patient Merge Request: ' . print_r($request->getErrors(), true));
             }
         }
     }
     echo CJavaScript::jsonEncode(array('success' => 1));
     Yii::app()->end();
 }
Ejemplo n.º 6
0
 public function actionDeleteAnaestheticAgent($id)
 {
     $agent = AnaestheticAgent::model()->findByPk($id);
     if (!$agent) {
         throw new CHttpException(404, 'Anaesthetic Agent not found: ' . $id);
     }
     if (Yii::app()->request->isPostRequest) {
         $agent->active = 0;
         if (!$agent->save()) {
             throw new CHttpException(500, 'Unable to delete Anaesthetic Agent: ' . $agent->name);
         }
         Audit::add('admin', 'delete', $id, null, array('model' => 'AnaestheticAgent'));
         $this->redirect('/admin/viewAnaestheticAgent');
     }
     Audit::add('admin', 'view', $id, null, array('model' => 'AnaestheticAgent'));
     $this->render('/admin/deleteanaestheticagent', array('agent' => $agent));
 }
Ejemplo n.º 7
0
 public function actionEditEmailRecipient($id)
 {
     $model = OphCoTherapyapplication_Email_Recipient::model()->findByPk((int) $id);
     if (isset($_POST['OphCoTherapyapplication_Email_Recipient'])) {
         $model->attributes = $_POST['OphCoTherapyapplication_Email_Recipient'];
         if ($model->save()) {
             Audit::add('admin', 'update', serialize($model->attributes), false, array('module' => 'OphCoTherapyapplication', 'model' => 'OphCoTherapyapplication_Email_Recipient'));
             Yii::app()->user->setFlash('success', 'Email recipient updated');
             $this->redirect(array('viewEmailRecipients'));
         }
     }
     $this->render('update', array('model' => $model, 'title' => 'Email Recipient', 'cancel_uri' => '/OphCoTherapyapplication/admin/viewEmailRecipients'));
 }
Ejemplo n.º 8
0
 public function actionSearch()
 {
     // Check that we have a valid set of search criteria
     $search_terms = array('hos_num' => null, 'nhs_num' => null, 'first_name' => null, 'last_name' => null);
     foreach ($search_terms as $search_term => $search_value) {
         if (isset($_GET[$search_term]) && ($search_value = trim($_GET[$search_term]))) {
             // Pad hos_num
             if ($search_term == 'hos_num') {
                 $search_value = sprintf('%07s', $search_value);
             }
             $search_terms[$search_term] = $search_value;
         }
     }
     // if we are on a dev environment, this allows more flexible search terms (i.e. just a first name or surname - useful for testing
     // the multiple search results view. If we are live, enforces controls over search terms.
     if (!YII_DEBUG && !$search_terms['hos_num'] && !$search_terms['nhs_num'] && !($search_terms['first_name'] && $search_terms['last_name'])) {
         Yii::app()->user->setFlash('warning.invalid-search', 'Please enter a valid search.');
         $this->redirect(Yii::app()->homeUrl);
     }
     $search_terms = CHtml::encodeArray($search_terms);
     switch (@$_GET['sort_by']) {
         case 0:
             $sort_by = 'hos_num*1';
             break;
         case 1:
             $sort_by = 'title';
             break;
         case 2:
             $sort_by = 'first_name';
             break;
         case 3:
             $sort_by = 'last_name';
             break;
         case 4:
             $sort_by = 'dob';
             break;
         case 5:
             $sort_by = 'gender';
             break;
         case 6:
             $sort_by = 'nhs_num*1';
             break;
         default:
             $sort_by = 'hos_num*1';
     }
     $sort_dir = @$_GET['sort_dir'] == 0 ? 'asc' : 'desc';
     $page_num = (int) @$_GET['page_num'];
     $page_size = 20;
     $model = new Patient();
     $model->hos_num = $search_terms['hos_num'];
     $model->nhs_num = $search_terms['nhs_num'];
     $dataProvider = $model->search(array('currentPage' => $page_num, 'pageSize' => $page_size, 'sortBy' => $sort_by, 'sortDir' => $sort_dir, 'first_name' => CHtml::decode($search_terms['first_name']), 'last_name' => CHtml::decode($search_terms['last_name'])));
     $nr = $model->search_nr(array('first_name' => CHtml::decode($search_terms['first_name']), 'last_name' => CHtml::decode($search_terms['last_name'])));
     if ($nr == 0) {
         Audit::add('search', 'search-results', implode(',', $search_terms) . " : No results");
         $message = 'Sorry, no results ';
         if ($search_terms['hos_num']) {
             $message .= 'for Hospital Number <strong>"' . $search_terms['hos_num'] . '"</strong>';
         } elseif ($search_terms['nhs_num']) {
             $message .= 'for NHS Number <strong>"' . $search_terms['nhs_num'] . '"</strong>';
         } elseif ($search_terms['first_name'] && $search_terms['last_name']) {
             $message .= 'for Patient Name <strong>"' . $search_terms['first_name'] . ' ' . $search_terms['last_name'] . '"</strong>';
         } else {
             $message .= 'found for your search.';
         }
         Yii::app()->user->setFlash('warning.no-results', $message);
         $this->redirect(Yii::app()->homeUrl);
     } elseif ($nr == 1) {
         foreach ($dataProvider->getData() as $item) {
             $this->redirect(array('patient/view/' . $item->id));
         }
     } else {
         $this->renderPatientPanel = false;
         $pages = ceil($nr / $page_size);
         $this->render('results', array('data_provider' => $dataProvider, 'pages' => $pages, 'page_num' => $page_num, 'items_per_page' => $page_size, 'total_items' => $nr, 'search_terms' => $search_terms, 'sort_by' => (int) @$_GET['sort_by'], 'sort_dir' => (int) @$_GET['sort_dir']));
     }
 }
Ejemplo n.º 9
0
 public function actionDeleteCommissioningBodyServiceTypes()
 {
     $criteria = new CDbCriteria();
     $criteria->addInCondition('id', @$_POST['commissioning_body_service_type']);
     if (!($er = CommissioningBodyServiceType::model()->deleteAll($criteria))) {
         throw new Exception("Unable to delete CommissioningBodyServiceTypes: " . print_r($er->getErrors(), true));
     }
     Audit::add('admin-CommissioningBodyServiceType', 'delete');
     echo "1";
 }
Ejemplo n.º 10
0
 /**
  * @param $type
  * @throws Exception
  */
 protected function audit($type, $data = null)
 {
     Audit::add('admin-' . $this->modelName, $type, $data);
 }
Ejemplo n.º 11
0
 /**
  * Allows generic CRUD operations on models.
  *
  * @param string $title   The title of the form to be rendered
  * @param string $model   The model for which we are generating a form
  * @param array  $options An array of options that will configure how the form is generated.
  *                        label_field - Will set which field is displayed as a text input for the model
  *                        extra_fields - An array of arrays for which extra fields to render. Each array should contain
  *                        an attribute of the model in assigned to field. Passing a type and model will allow
  *                        either a dropdown or search box for finding related objects eg:
  *                        array(
  *                        'field' => 'site_id',
  *                        'type' => 'lookup',
  *                        'model' => 'Site'
  *                        ),
  *                        filter_fields - Will allow you to filter results, expects an array the same as extra_fields
  * @param int    $key     - if provided will only generate a single row for a null instance of the $model (for ajax additions)
  */
 protected function genericAdmin($title, $model, array $options = array(), $key = null)
 {
     $options = array_merge(array('label_field' => $model::SELECTION_LABEL_FIELD, 'extra_fields' => array(), 'filter_fields' => array(), 'filters_ready' => true, 'label_extra_field' => false), $options);
     $columns = $model::model()->metadata->columns;
     foreach ($options['extra_fields'] as $extraKey => $extraField) {
         switch ($extraField['type']) {
             case 'lookup':
                 $options['extra_fields'][$extraKey]['allow_null'] = $columns[$extraField['field']]->allowNull;
                 break;
         }
         if ($extraField['field'] === $options['label_field']) {
             $options['label_extra_field'] = true;
         }
     }
     foreach ($options['filter_fields'] as $filterKey => $filterField) {
         $options['filter_fields'][$filterKey]['value'] = null;
         if (isset($_GET[$filterField['field']])) {
             $options['filter_fields'][$filterKey]['value'] = $_GET[$filterField['field']];
         }
         if ($options['filter_fields'][$filterKey]['value'] === null && !$columns[$filterField['field']]->allowNull) {
             $options['filters_ready'] = false;
         }
     }
     $items = array();
     $errors = array();
     $options['display_order'] = false;
     if ($key !== null) {
         $items = array($key => new $model());
         $options['get_row'] = true;
         if ($model::model()->hasAttribute('display_order')) {
             $options['display_order'] = true;
         }
         $this->renderPartial('//admin/generic_admin', array('title' => $title, 'model' => $model, 'items' => $items, 'errors' => $errors, 'options' => $options), false, true);
     } else {
         if ($options['filters_ready']) {
             if (Yii::app()->request->isPostRequest) {
                 $tx = Yii::app()->db->beginTransaction();
                 $j = 0;
                 foreach ((array) @$_POST['id'] as $i => $id) {
                     if ($id) {
                         $item = $model::model()->findByPk($id);
                         $new = false;
                     } else {
                         $item = new $model();
                         $new = true;
                     }
                     $attributes = $item->getAttributes();
                     if (!empty($_POST[$options['label_field']][$i])) {
                         $item->{$options['label_field']} = $_POST[$options['label_field']][$i];
                         if ($item->hasAttribute('display_order')) {
                             $options['display_order'] = true;
                             $item->display_order = $j + 1;
                         }
                         if (array_key_exists('active', $attributes)) {
                             $item->active = isset($_POST['active'][$i]) || $item->isNewRecord ? 1 : 0;
                         }
                         foreach ($options['extra_fields'] as $field) {
                             $name = $field['field'];
                             $item->{$name} = @$_POST[$name][$i];
                         }
                         if ($item->hasAttribute('default')) {
                             if (isset($_POST['default']) && $_POST['default'] !== 'NONE' && $_POST['default'] == $j) {
                                 $item->default = 1;
                             } else {
                                 $item->default = 0;
                             }
                         }
                         foreach ($options['filter_fields'] as $field) {
                             $item->{$field['field']} = $field['value'];
                         }
                         if ($new || $item->getAttributes() != $attributes) {
                             if (!$item->save()) {
                                 $errors = $item->getErrors();
                                 foreach ($errors as $error) {
                                     $errors[$i] = $error[0];
                                 }
                             }
                             Audit::add('admin', $new ? 'create' : 'update', $item->primaryKey, null, array('module' => is_object($this->module) ? $this->module->id : 'core', 'model' => $model::getShortModelName()));
                         }
                         $items[] = $item;
                         ++$j;
                     }
                 }
                 if (empty($errors)) {
                     $criteria = new CDbCriteria();
                     if ($items) {
                         $criteria->addNotInCondition('id', array_map(function ($i) {
                             return $i->id;
                         }, $items));
                     }
                     $this->addFilterCriteria($criteria, $options['filter_fields']);
                     $to_delete = $model::model()->findAll($criteria);
                     foreach ($to_delete as $item) {
                         if (!$item->delete()) {
                             throw new Exception("Unable to delete {$model}:{$item->primaryKey}");
                         }
                         Audit::add('admin', 'delete', $item->primaryKey, null, array('module' => is_object($this->module) ? $this->module->id : 'core', 'model' => $model::getShortModelName()));
                     }
                     $tx->commit();
                     Yii::app()->user->setFlash('success', 'List updated.');
                     $this->redirect(Yii::app()->request->url);
                 } else {
                     $tx->rollback();
                 }
             } else {
                 $order = array();
                 if ($model::model()->hasAttribute('display_order')) {
                     $order = array('order' => 'display_order');
                     $options['display_order'] = true;
                 }
                 $crit = new CDbCriteria($order);
                 $this->addFilterCriteria($crit, $options['filter_fields']);
                 $items = $model::model()->findAll($crit);
             }
         }
         $this->render('//admin/generic_admin', array('title' => $title, 'model' => $model, 'items' => $items, 'errors' => $errors, 'options' => $options));
     }
 }
 /**
  * @param int $queueset_id
  * @param int $user_ids[]
  *
  * @throws \Exception
  */
 public function setPermisssionedUsers($queueset_id, $user_ids, $role = null)
 {
     $qs = $this->readModel($queueset_id);
     $users = array();
     foreach ($user_ids as $id) {
         if (!($user = \User::model()->findByPk($id))) {
             throw new \Exception("User not found for id {$id}");
         }
         $users[] = $user;
     }
     $role_item = null;
     if ($role) {
         $role_item = Yii::app()->authManager->getAuthItem($role);
         if (!$role_item) {
             throw new \Exception("Unrecognised role {$role} for permissioning");
         }
     }
     $transaction = Yii::app()->db->getCurrentTransaction() === null ? Yii::app()->db->beginTransaction() : false;
     try {
         $qs->permissioned_users = $users;
         $qs->save();
         \Audit::add('admin', 'set-permissions', $qs->id, null, array('module' => 'PatientTicketing', 'model' => $qs->getShortModelName()));
         if ($role_item) {
             foreach ($users as $user) {
                 if (!$role_item->getAssignment($user->id)) {
                     $role_item->assign($user->id);
                     \Audit::add('admin-User', 'assign-role', "{$user->id}:{$role_item->name}");
                 }
             }
         }
         if ($transaction) {
             $transaction->commit();
         }
     } catch (\Exception $e) {
         if ($transaction) {
             $transaction->rollback();
         }
         throw $e;
     }
 }
Ejemplo n.º 13
0
 /**
  * Deactivate a Queue, and if $cascade is true, then deactivate it's children.
  *
  * @param $queue
  * @param bool $cascade
  */
 protected function deactivateQueue($queue, $cascade = true)
 {
     $queue->active = false;
     if ($cascade) {
         foreach ($queue->outcome_queues as $oc) {
             $this->deactivateQueue($oc);
         }
     }
     $queue->save();
     \Audit::add('admin', 'update', $queue->id, null, array('module' => 'PatientTicketing', 'model' => $queue->getShortModelName()));
 }
Ejemplo n.º 14
0
 /**
  * Moving event from one episode to another.
  * 
  * @param int   $newEpisodeId
  * @param array $events
  *
  * @return bool
  *
  * @throws Exception
  */
 public function updateEventsEpisodeId($newEpisodeId, $events)
 {
     foreach ($events as $event) {
         $msg = 'Event ' . $event->id . ' moved from Episode ' . $event->episode_id . ' to ' . $newEpisodeId;
         $event->episode_id = $newEpisodeId;
         if ($event->save()) {
             $this->addLog($msg);
             Audit::add('Patient Merge', 'Event moved episode', $msg);
         } else {
             throw new Exception('Failed to save Event: ' . print_r($event->errors, true));
         }
     }
     return true;
 }
Ejemplo n.º 15
0
 /**
  * Disable or enable a OphTrOperationbooking_ScheduleOperation_PatientUnavailableReason.
  *
  * @throws Exception
  */
 public function actionSwitchEnabledSessionUnavailableReason()
 {
     if (!($reason = OphTrOperationbooking_Operation_Session_UnavailableReason::model()->findByPk(@$_POST['id']))) {
         throw new Exception('Session Unavailable Reason not found: ' . @$_POST['id']);
     }
     if ($reason->enabled) {
         $reason->enabled = 0;
         $action = 'disabled';
     } else {
         $reason->enabled = 1;
         $action = 'enabled';
     }
     if (!$reason->save()) {
         throw new Exception('Unexpected error changing enabled status for Session Unavailable Reason ' . print_r($reason->getErrors(), true));
     }
     Audit::add('admin', $action, serialize($_POST), false, array('module' => 'OphTrOperationbooking', 'model' => 'OphTrOperationbooking_Operation_Session_UnavailableReason'));
 }
Ejemplo n.º 16
0
 /**
  * Delete a post op drug.
  *
  * @throws Exception
  */
 public function actionDeletePostOpDrugs()
 {
     $result = 1;
     foreach (OphTrOperationnote_PostopDrug::model()->findAllByPk(@$_POST['drugs']) as $drug) {
         $drug->active = 0;
         if (!$drug->save()) {
             $result = 0;
         } else {
             Audit::add('admin', 'delete', $drug->id, null, array('module' => 'OphTrOperationnote', 'model' => 'OphTrOperationnote_PostopDrug'));
         }
     }
     echo $result;
 }
 /**
  * if this element is linked to a secondary diagnosis that still exists, it will be removed.
  */
 protected function cleanUpSecondaryDiagnosis()
 {
     if ($sd = $this->_getSecondaryDiagnosis()) {
         $disorder = $sd->disorder;
         $audit_data = serialize($sd->attributes);
         $sd->delete();
         \Audit::add('SecondaryDiagnosis', 'delete', $sd->id, null, array('patient_id' => $sd->patient_id));
         Yii::app()->user->setFlash('warning.alert', "Disorder '" . $disorder->term . "' has been removed because DR Grading was deleted.");
     }
 }
Ejemplo n.º 18
0
 /**
  * Ajax action to retrieve diary data.
  */
 public function actionSearch()
 {
     Audit::add('diary', 'search');
     $list = $this->renderPartial('_list', array('diary' => $this->getDiaryTheatres($_POST), 'assetPath' => $this->assetPath, 'ward_id' => @$_POST['ward-id']), true, true);
     echo json_encode(array('status' => 'success', 'data' => $list));
 }
Ejemplo n.º 19
0
 public function actionEditMacro($id)
 {
     if (!($macro = LetterMacro::model()->findByPk($id))) {
         throw new Exception("LetterMacro not found: {$id}");
     }
     $errors = array();
     if (!empty($_POST)) {
         $macro->attributes = $_POST['LetterMacro'];
         if (!$macro->validate()) {
             $errors = $macro->errors;
         } else {
             if (!$macro->save()) {
                 throw new Exception('Unable to save macro: ' . print_r($macro->errors, true));
             }
             Audit::add('admin', 'update', $macro->id, null, array('module' => 'OphCoCorrespondence', 'model' => 'LetterMacro'));
             $this->redirect('/OphCoCorrespondence/admin/letterMacros');
         }
     } else {
         Audit::add('admin', 'view', $macro->id, null, array('module' => 'OphCoCorrespondence', 'model' => 'LetterMacro'));
     }
     $this->render('_macro', array('macro' => $macro, 'errors' => $errors));
 }
Ejemplo n.º 20
0
 /**
  * Set operations printed letter state.
  */
 public function actionConfirmPrinted()
 {
     Audit::add('waiting list', 'confirm');
     foreach ($_POST['operations'] as $operation_id) {
         if ($operation = Element_OphTrOperationbooking_Operation::Model()->findByPk($operation_id)) {
             if (Yii::app()->user->checkAccess('admin') and isset($_POST['adminconfirmto']) and $_POST['adminconfirmto'] != 'OFF' and $_POST['adminconfirmto'] != '') {
                 $operation->confirmLetterPrinted($_POST['adminconfirmto'], $_POST['adminconfirmdate']);
             } else {
                 $operation->confirmLetterPrinted();
             }
         }
     }
 }
Ejemplo n.º 21
0
 /**
  * Audit Wrapper.
  *
  * @param $target
  * @param $action
  * @param null  $data
  * @param null  $log_message
  * @param array $properties
  *
  * @throws Exception
  */
 protected function audit($target, $action, $data = null, $log_message = null, $properties = array())
 {
     if (!$this->do_audit) {
         return;
     }
     if (!isset($properties['user_id'])) {
         $properties['user_id'] = $this->getCurrentUser()->id;
     }
     if (is_array($data)) {
         $data = json_encode($data);
     }
     Audit::add($target, $action, $data, $log_message, $properties);
 }
Ejemplo n.º 22
0
 public function actionSearch()
 {
     $term = \Yii::app()->request->getParam('term', '');
     $patientSearch = new PatientSearch();
     $dataProvider = $patientSearch->search($term);
     $itemCount = $dataProvider->totalItemCount;
     $search_terms = $patientSearch->getSearchTerms();
     if ($itemCount == 0) {
         Audit::add('search', 'search-results', implode(',', $search_terms) . ' : No results');
         $message = 'Sorry, no results ';
         if ($search_terms['hos_num']) {
             $message .= 'for Hospital Number <strong>"' . $search_terms['hos_num'] . '"</strong>';
             // check if the record was merged into another record
             $criteria = new CDbCriteria();
             $criteria->compare('secondary_hos_num', $search_terms['hos_num']);
             $criteria->compare('status', PatientMergeRequest::STATUS_MERGED);
             $patientMergeRequest = PatientMergeRequest::model()->find($criteria);
             if ($patientMergeRequest) {
                 $message = 'Hospital Number <strong>' . $search_terms['hos_num'] . '</strong> was merged into <strong>' . $patientMergeRequest->primary_hos_num . '</strong>';
             }
         } elseif ($search_terms['nhs_num']) {
             $message .= 'for NHS Number <strong>"' . $search_terms['nhs_num'] . '"</strong>';
         } elseif ($search_terms['first_name'] && $search_terms['last_name']) {
             $message .= 'for Patient Name <strong>"' . $search_terms['first_name'] . ' ' . $search_terms['last_name'] . '"</strong>';
         } else {
             $message .= 'found for your search.';
         }
         Yii::app()->user->setFlash('warning.no-results', $message);
         $this->redirect(Yii::app()->homeUrl);
     } elseif ($itemCount == 1) {
         foreach ($dataProvider->getData() as $item) {
             $this->redirect(array('patient/view/' . $item->id));
         }
     } else {
         $this->renderPatientPanel = false;
         $this->render('results', array('data_provider' => $dataProvider, 'page_num' => \Yii::app()->request->getParam('Patient_page', 0), 'total_items' => $itemCount, 'term' => $term, 'search_terms' => $patientSearch->getSearchTerms(), 'sort_by' => (int) \Yii::app()->request->getParam('sort_by', null), 'sort_dir' => (int) \Yii::app()->request->getParam('sort_dir', null)));
     }
 }
Ejemplo n.º 23
0
 /**
  * @param $target
  * @param $action
  * @param null $data
  * @param null $log_message
  * @param array $properties
  * @throws Exception
  */
 public function audit($target, $action, $data = null, $log_message = null, $properties = array())
 {
     foreach (array('patient_id', 'episode_id', 'event_id', 'user_id', 'site_id', 'firm_id') as $field) {
         if (isset($this->{$field}) && !isset($properties[$field])) {
             $properties[$field] = $this->{$field};
         }
     }
     Audit::add($target, $action, $data, $log_message, $properties);
 }
Ejemplo n.º 24
0
 /**
  * Authenticates a user.
  *
  * Uses either BASIC or LDAP authentication. BASIC authenticates against
  * the openeyes DB. LDAP uses whichever LDAP is specified in the params.php
  * config file.
  *
  * @return boolean whether authentication succeeds.
  * @throws
  */
 public function authenticate($force = false)
 {
     if (!in_array(Yii::app()->params['ldap_method'], array('native', 'zend'))) {
         throw new Exception('Unsupported LDAP authentication method: ' . Yii::app()->params['ldap_method'] . ', please use native or zend.');
     }
     Yii::app()->event->dispatch('user_before_login', array('username' => $this->username));
     /**
      * Usernames are case sensitive
      */
     $user = User::model()->find('username = ?', array($this->username));
     if ($user === null) {
         Audit::add('login', 'login-failed', null, "User not found in local database: {$this->username}");
         $this->errorCode = self::ERROR_USERNAME_INVALID;
         return false;
     } elseif (!$force && $user->active != 1) {
         $user->audit('login', 'login-failed', null, "User not active and so cannot login: {$this->username}");
         $this->errorCode = self::ERROR_USER_INACTIVE;
         return false;
     } elseif (!$force && !Yii::app()->getAuthManager()->checkAccess('OprnLogin', $user->id)) {
         $user->audit('login', 'login-failed', "User has not been assigned OprnLogin and so cannot login: {$this->username}", true);
         $this->errorCode = self::ERROR_USER_INACTIVE;
         return false;
     }
     if (in_array($user->username, Yii::app()->params['local_users'])) {
         Yii::app()->params['auth_source'] = 'BASIC';
     }
     $this->password = utf8_decode($this->password);
     /**
      * Here we diverge depending on the authentication source.
      */
     if (Yii::app()->params['auth_source'] == 'LDAP') {
         /**
          * Required for LDAP authentication
          */
         if (Yii::app()->params['ldap_method'] == 'zend') {
             Yii::import('application.vendors.*');
             require_once 'Zend/Ldap.php';
             /**
              * Check with LDAP for authentication
              */
             $options = array('host' => Yii::app()->params['ldap_server'], 'port' => Yii::app()->params['ldap_port'], 'username' => Yii::app()->params['ldap_admin_dn'], 'password' => Yii::app()->params['ldap_password'], 'baseDn' => Yii::app()->params['ldap_admin_dn'], 'useStartTls' => false);
             $ldap = $this->getLdap($options);
             /**
              * Try and bind to the login details provided. This indicates if
              * the user is in LDAP.
              */
             try {
                 $ldap->bind("cn=" . $this->username . "," . Yii::app()->params['ldap_dn'], $this->password);
             } catch (Exception $e) {
                 /**
                  * User not authenticated via LDAP
                  */
                 $audit = new Audit();
                 $audit->action = "login-failed";
                 $audit->target_type = "login";
                 $audit->user_id = $user->id;
                 $audit->data = "Login failed for user {$this->username}: LDAP authentication failed: " . $e->getMessage() . ": " . $this->username;
                 $audit->save();
                 OELog::log("Login failed for user {$this->username}: LDAP authentication failed: " . $e->getMessage(), $this->username);
                 $this->errorCode = self::ERROR_USERNAME_INVALID;
                 return false;
             }
             /**
              * User is in LDAP, get their details.
              */
             $info = $ldap->getEntry("cn=" . $this->username . "," . Yii::app()->params['ldap_dn'], array('givenname', 'sn', 'mail'));
         } else {
             if (!($link = ldap_connect(Yii::app()->params['ldap_server']))) {
                 throw new Exception('Unable to connect to LDAP server.');
             }
             ldap_set_option($link, LDAP_OPT_NETWORK_TIMEOUT, Yii::app()->params['ldap_native_timeout']);
             if (!@ldap_bind($link, "cn={$this->username}," . Yii::app()->params['ldap_dn'], $this->password)) {
                 $audit = new Audit();
                 $audit->action = "login-failed";
                 $audit->target_type = "login";
                 $audit->user_id = $user->id;
                 $audit->data = "Login failed for user {$this->username}: LDAP authentication failed: " . ldap_error($link);
                 $audit->save();
                 OELog::log("Login failed for user {$this->username}: LDAP authentication failed: " . ldap_error($link));
                 $this->errorCode = self::ERROR_USERNAME_INVALID;
                 return false;
             }
             $attempts = isset(Yii::app()->params['ldap_info_retries']) ? Yii::app()->params['ldap_info_retries'] : 1;
             for ($i = 0; $i < $attempts; $i++) {
                 if ($i > 0 && isset(Yii::app()->params['ldap_info_retry_delay'])) {
                     sleep(Yii::app()->params['ldap_info_retry_delay']);
                 }
                 $sr = ldap_search($link, "cn={$this->username}," . Yii::app()->params['ldap_dn'], "cn={$this->username}");
                 $info = ldap_get_entries($link, $sr);
                 if (isset($info[0])) {
                     break;
                 }
             }
             if (!isset($info[0])) {
                 throw new Exception("Failed to retrieve ldap info for user {$user->username}: " . ldap_error($link) . " [" . print_r($info, true) . "]");
             }
             $info = $info[0];
         }
         /**
          * Update user db record with details from LDAP.
          */
         if (Yii::app()->params['ldap_update_name']) {
             if (isset($info['givenname'][0])) {
                 $user->first_name = $info['givenname'][0];
             }
             if (isset($info['sn'][0])) {
                 $user->last_name = $info['sn'][0];
             }
         }
         if (Yii::app()->params['ldap_update_email']) {
             if (isset($info['mail'][0])) {
                 $user->email = $info['mail'][0];
             }
         }
         if (!$user->save()) {
             $user->audit('login', 'login-failed', null, "Login failed for user {$this->username}: unable to update user with details from LDAP: " . print_r($user->getErrors(), true));
             throw new SystemException('Unable to update user with details from LDAP: ' . print_r($user->getErrors(), true));
         }
     } elseif (Yii::app()->params['auth_source'] == 'BASIC') {
         if (!$force && !$user->validatePassword($this->password)) {
             $this->errorCode = self::ERROR_PASSWORD_INVALID;
             $user->audit('login', 'login-failed', null, "Login failed for user {$this->username}: invalid password");
             return false;
         }
     } else {
         /**
          * Unknown auth_source, error
          */
         $user->audit('login', 'login-failed', null, "Login failed for user {$this->username}: unknown auth source: " . Yii::app()->params['auth_source']);
         throw new SystemException('Unknown auth_source: ' . Yii::app()->params['auth_source']);
     }
     $this->_id = $user->id;
     $this->username = $user->username;
     $this->errorCode = self::ERROR_NONE;
     // Get all the user's firms and put them in a session
     $app = Yii::app();
     $firms = array();
     foreach ($user->getAvailableFirms() as $firm) {
         $firms[$firm->id] = $this->firmString($firm);
     }
     if (!count($firms)) {
         $user->audit('login', 'login-failed', null, "Login failed for user {$this->username}: user has no firm rights and cannot use the system");
         throw new Exception('User has no firm rights and cannot use the system.');
     }
     natcasesort($firms);
     $app->session['user'] = $user;
     $app->session['firms'] = $firms;
     reset($firms);
     // Select firm
     if ($user->last_firm_id) {
         $app->session['selected_firm_id'] = $user->last_firm_id;
     } elseif (count($user->firms)) {
         // Set the firm to one the user is associated with
         $userFirms = $user->firms;
         $app->session['selected_firm_id'] = $userFirms[0]->id;
     } else {
         // The user doesn't have firms of their own to select from so we select
         // one arbitrarily
         $app->session['selected_firm_id'] = key($firms);
     }
     // Select site
     if ($user->last_site_id) {
         $app->session['selected_site_id'] = $user->last_site_id;
     } elseif ($default_site = Site::model()->getDefaultSite()) {
         $app->session['selected_site_id'] = $default_site->id;
     } else {
         throw new CException('Cannot find default site');
     }
     $user->audit('login', 'login-successful', null, "User " . strtoupper($this->username) . " logged in");
     return true;
 }
Ejemplo n.º 25
0
 public function actionEditLaserOperator($id)
 {
     if (!($laser_operator = OphTrLaser_Laser_Operator::model()->findByPk($id))) {
         throw new Exception("Laser operator not found: {$id}");
     }
     $errors = array();
     if (!empty($_POST)) {
         if ($laser_operator->id) {
             if (OphTrLaser_Laser_Operator::model()->find('id != ? and user_id = ?', array($laser_operator->id, $_POST['OphTrLaser_Laser_Operator']['user_id']))) {
                 $errors[] = array('This user is already in the list.');
             }
         }
         if (empty($errors)) {
             $laser_operator->attributes = $_POST['OphTrLaser_Laser_Operator'];
             if (!$laser_operator->save()) {
                 $errors = $laser_operator->getErrors();
             } else {
                 Audit::add('admin', 'update', serialize(array_merge(array('id' => $id), $_POST)), false, array('module' => 'OphTrLaser', 'model' => 'OphTrLaser_Laser_Operator'));
                 $this->redirect(array('/OphTrLaser/admin/viewLaserOperators'));
             }
         }
     }
     Audit::add('admin', 'view', $id, false, array('module' => 'OphTrLaser', 'model' => 'OphTrLaser_Laser_Operator'));
     $this->render('/admin/edit_laser_operator', array('laser_operator' => $laser_operator, 'errors' => $errors));
 }
 /**
  * Delete the queue and the queues that are are solely dependent on it.
  *
  * @param $queue_id
  *
  * @throws \Exception
  * @throws \Exception
  */
 public function delete($queue_id)
 {
     $transaction = Yii::app()->db->getCurrentTransaction() === null ? Yii::app()->db->beginTransaction() : false;
     try {
         $queue = $this->readModel($queue_id);
         // remove dependendent outcomes
         $remove_ids = $queue->getDependentQueueIds();
         $remove_ids[] = $queue_id;
         // how I'd do it if BaseActiveRecordVersioned supported delete with an in condition
         /*
         $criteria = new \CDbCriteria();
         $criteria->addInCondition('outcome_queue_id', $remove_ids);
         $criteria->addInCondition('queue_id', $remove_ids, 'OR');
         models\QueueOutcome::model()->deleteAll($criteria);
         
         // remove dependent and actual queues
         $criteria = new \CDbCriteria();
         $criteria->addInCondition($this->model->getPrimaryKey(), $remove_ids);
         $this->model->deleteAll($criteria);
         */
         // instead ...
         foreach ($remove_ids as $rid) {
             $criteria = new \CDbCriteria();
             $criteria->addColumnCondition(array('outcome_queue_id' => $rid, 'queue_id' => $rid), 'OR');
             models\QueueOutcome::model()->deleteAll($criteria);
             $this->model->deleteByPk($rid);
         }
         \Audit::add('admin', 'delete', $queue->id, null, array('module' => 'PatientTicketing', 'model' => $queue->getShortModelName()));
         if ($transaction) {
             $transaction->commit();
         }
     } catch (\Exception $e) {
         if ($transaction) {
             $transaction->rollback();
         }
         throw $e;
     }
 }
 /**
  * main method to run the command for file collection creation.
  *
  * @TODO: look for a summary text file to include.
  * @TODO: search for existing file collections and update instead of adding.
  *
  * @param array $args
  *
  * @return int|void
  */
 public function run($args)
 {
     if (!count($args) == 1) {
         $this->usageError('missing source path argument');
     }
     if (!is_readable($args[0])) {
         $this->usageError('cannot read specified source path ' . $args[0]);
     }
     $base_path = $args[0];
     // read directory structure into data
     $file_list = $this->buildFileList($base_path, './');
     $file_ext_regexp = implode('|', $this->file_extensions);
     $sets = array();
     // determine the file collections to be created
     foreach ($file_list as $fname => $details) {
         if (preg_match('/' . $file_ext_regexp . '$/', $fname)) {
             $path = str_replace(DIRECTORY_SEPARATOR, ' - ', dirname($fname));
             if (!@$sets[$path]) {
                 $summary_text = $this->summary_text_default;
                 $summary_filepath = $base_path . dirname($fname) . DIRECTORY_SEPARATOR . $this->summary_filename;
                 if ($this->summary_filename && file_exists($summary_filepath)) {
                     // read the summary text in from the file
                     $summary_text = file_get_contents($summary_filepath);
                 }
                 $sets[$path] = array('summary' => $summary_text, 'files' => array($details));
             } else {
                 $sets[$path]['files'][] = $details;
             }
         }
     }
     $created = 0;
     $modified = 0;
     // iterate through and create the file collections.
     foreach ($sets as $set_name => $set_details) {
         $created_flag = false;
         $transaction = Yii::app()->getDb()->beginTransaction();
         $pf_list = array();
         $pf_ids = array();
         try {
             foreach ($set_details['files'] as $details) {
                 $pf = ProtectedFile::createFromFile($details['source']);
                 if ($pf->save()) {
                     $pf_ids[] = $pf->id;
                     $pf_list[] = $pf;
                 } else {
                     foreach ($pf_list as $pf) {
                         $pf->delete();
                     }
                     break;
                 }
             }
             // update the existing file collection if there is one
             $criteria = new CDbCriteria();
             $criteria->addCondition('name = :nm');
             $criteria->params = array(':nm' => $set_name);
             if (!($fc = OphCoTherapyapplication_FileCollection::model()->find($criteria))) {
                 $fc = new OphCoTherapyapplication_FileCollection();
                 $fc->name = $set_name;
                 $created_flag = true;
             }
             $fc->summary = $set_details['summary'];
             if (!$fc->validate()) {
                 echo "unexpected validation error with file collection\n";
                 var_dump($fc->getErrors());
                 $transaction->rollback();
             } else {
                 if ($fc->save()) {
                     $fc->updateFiles($pf_ids);
                     Audit::add('admin', 'create', $fc->id, null, array('module' => 'OphCoTherapyapplication', 'model' => 'OphCoTherapyapplication_FileCollection'));
                     $transaction->commit();
                     $created_flag ? $created++ : $modified++;
                 } else {
                     foreach ($pf_list as $pf) {
                         $pf->delete();
                     }
                     $transaction->rollback();
                 }
             }
         } catch (Exception $e) {
             echo $e->getMessage();
             foreach ($pf_list as $pf) {
                 $pf->delete();
             }
             $transaction->rollback();
         }
     }
     echo 'Processing complete, ' . $created . ' collections created, ' . $modified . " collections updated\n";
 }
Ejemplo n.º 28
0
 /**
  * Set status to inactive on models missing from the CSV file.
  *
  * @param type $type GP
  */
 private function markInactiveMissingModels($type)
 {
     $dbTable = $this->getTableNameByType($type);
     $column = $dbTable == 'gp' ? 'nat_id' : 'code';
     $criteria = new CDbCriteria();
     $criteria->select = array('t.*');
     $criteria->join = "LEFT JOIN temp_{$dbTable} ON t.{$column} = temp_{$dbTable}.{$column}";
     $criteria->addCondition("temp_{$dbTable}.{$column} IS NULL");
     $criteria->addCondition('t.is_active = 1');
     $modelName = ucfirst($dbTable);
     $not_in_file = $modelName::model()->findAll($criteria);
     echo 'Set ' . count($not_in_file) . " {$type} to inactive... ";
     foreach ($not_in_file as $removed_instance) {
         $removed_instance->is_active = '0';
         if ($removed_instance->save() && $this->audit !== 'false') {
             Audit::add('ProcessHscicDataCommand', "{$type} ({$removed_instance->{$column}}) set to inactive");
         }
     }
     echo "OK\n\n";
 }
Ejemplo n.º 29
0
 /**
  * Wrapper for auditing calls on resource changes.
  *
  * @param $audit_type
  * @param null  $data
  * @param null  $msg
  * @param array $properties
  *
  * @throws \Exception
  */
 public function audit($audit_type, $data = null, $msg = null, $properties = array())
 {
     if ($data) {
         $data = array_merge($this->getAuditData(), $data);
     } else {
         $data = $this->getAuditData();
     }
     \Audit::add($this->getAuditTarget(), $audit_type, $data, null, $properties);
 }
Ejemplo n.º 30
0
 public function actionDeleteRemapValue($id)
 {
     if (!($model = RemapValue::model()->findByPk($id))) {
         throw new \CHttpException('404', 'Could not Xpath Remap');
     }
     $model->delete();
     \Audit::add('admin', 'update', serialize($model->attributes), false, array('module' => 'PASAPI', 'model' => '\\OEModule\\PASAPI\\models\\RemapValue'));
     \Yii::app()->user->setFlash('success', 'Remap Value "' . $model->input . '" for "' . $model->xpath->name . '" deleted');
     $this->redirect(array('viewRemapValues', 'id' => $model->xpath_id));
 }