Exemplo n.º 1
0
 /**
  * Standardise the dumping of an exception message into the kohana log. E.g.
  * try {
  *	   ... code that throws exception ...
  * } catch (Exception $e) {
  *   error::log_error('Error occurred whilst running some code', $e);
  * }
  *
  * @param string $msg A description of where the error occurred.
  * $param object $e The exception object.
  */
 public static function log_error($msg, $e)
 {
     kohana::log('error', '#' . $e->getCode() . ': ' . $msg . '. ' . $e->getMessage() . ' at line ' . $e->getLine() . ' in file ' . $e->getFile());
     // Double check the log threshold to avoid unnecessary work.
     if (kohana::config('config.log_threshold') == 4) {
         $trace = $e->getTrace();
         $output = "Stack trace:\n";
         for ($i = 0; $i < count($trace); $i++) {
             if (array_key_exists('file', $trace[$i])) {
                 $file = $trace[$i]['file'];
             } else {
                 $file = 'Unknown file';
             }
             if (array_key_exists('line', $trace[$i])) {
                 $line = $trace[$i]['line'];
             } else {
                 $line = 'Unknown';
             }
             if (array_key_exists('function', $trace[$i])) {
                 $function = $trace[$i]['function'];
             } else {
                 $function = 'Unknown function';
             }
             $output .= "\t" . $file . ' - line ' . $line . ' - ' . $function . "\n";
         }
         kohana::log('debug', $output);
     }
 }
Exemplo n.º 2
0
 /**
  * 构造方法
  */
 public function __construct($img_dir_name = '')
 {
     $upload_path = kohana::config('upload.directory');
     $this->img_dir_name = $img_dir_name ? $img_dir_name : $this->img_dir_name;
     $this->dir_name = $upload_path . '/' . $this->img_dir_name . '/';
     $this->no_img_file = $upload_path . '/no_img.gif';
 }
Exemplo n.º 3
0
 /**
  * Method to create a nonce, either from a service call (when the caller type is a website) or from the Warehouse
  * (when the caller type is an Indicia user.
  */
 public static function create_nonce($type, $website_id)
 {
     $nonce = sha1(time() . ':' . rand() . $_SERVER['REMOTE_ADDR'] . ':' . kohana::config('indicia.private_key'));
     $cache = new Cache();
     $cache->set($nonce, $website_id, $type, Kohana::config('indicia.nonce_life'));
     return $nonce;
 }
Exemplo n.º 4
0
 public function notify_admins($subject = NULL, $message = NULL)
 {
     // Don't show the exceptions for this operation to the user. Log them
     // instead
     try {
         if ($subject && $message) {
             $settings = kohana::config('settings');
             $from = array();
             $from[] = $settings['site_email'];
             $from[] = $settings['site_name'];
             $users = ORM::factory('user')->where('notify', 1)->find_all();
             foreach ($users as $user) {
                 if ($user->has(ORM::factory('role', 'admin'))) {
                     $address = $user->email;
                     $message .= "\n\n\n\n~~~~~~~~~~~~\n" . Kohana::lang('notifications.admin_footer') . "\n" . url::base() . "\n\n" . Kohana::lang('notifications.admin_login_url') . "\n" . url::base() . "admin";
                     if (!email::send($address, $from, $subject, $message, FALSE)) {
                         Kohana::log('error', "email to {$address} could not be sent");
                     }
                 }
             }
         } else {
             Kohana::log('error', "email to {$address} could not be sent\n\t\t\t\t - Missing Subject or Message");
         }
     } catch (Exception $e) {
         Kohana::log('error', "An exception occured " . $e->__toString());
     }
 }
Exemplo n.º 5
0
 /**
  * Sends an email alert
  */
 public static function _send_email_alert($post)
 {
     // Email Alerts, Confirmation Code
     $alert_email = $post->alert_email;
     $alert_lon = $post->alert_lon;
     $alert_lat = $post->alert_lat;
     $alert_radius = $post->alert_radius;
     $alert_code = text::random('alnum', 20);
     $settings = kohana::config('settings');
     $to = $alert_email;
     $from = array();
     $from[] = $settings['alerts_email'] ? $settings['alerts_email'] : $settings['site_email'];
     $from[] = $settings['site_name'];
     $subject = $settings['site_name'] . " " . Kohana::lang('alerts.verification_email_subject');
     $message = Kohana::lang('alerts.confirm_request') . url::site() . 'alerts/verify?c=' . $alert_code . "&e=" . $alert_email;
     if (email::send($to, $from, $subject, $message, TRUE) == 1) {
         $alert = ORM::factory('alert');
         $alert->alert_type = self::EMAIL_ALERT;
         $alert->alert_recipient = $alert_email;
         $alert->alert_code = $alert_code;
         $alert->alert_lon = $alert_lon;
         $alert->alert_lat = $alert_lat;
         $alert->alert_radius = $alert_radius;
         if (isset($_SESSION['auth_user'])) {
             $alert->user_id = $_SESSION['auth_user']->id;
         }
         $alert->save();
         self::_add_categories($alert, $post);
         return TRUE;
     }
     return FALSE;
 }
Exemplo n.º 6
0
 /** 
  * Code for the insertMapSquaresFor... methods, which takes the table alias as a parameter in order to be generic.
  */
 private static function insertMapSquares($ids, $alias, $size, $db = null)
 {
     if (count($ids) > 0) {
         static $srid;
         if (!isset($srid)) {
             $srid = kohana::config('sref_notations.internal_srid');
         }
         if (!$db) {
             $db = new Database();
         }
         $idlist = implode(',', $ids);
         // Seems much faster to break this into small queries than one big left join.
         $smpInfo = $db->query("SELECT DISTINCT s.id, st_astext(coalesce(s.geom, l.centroid_geom)) as geom, o.confidential, GREATEST(o.sensitivity_precision, s.privacy_precision, {$size}) as size, \n          coalesce(s.entered_sref_system, l.centroid_sref_system) as entered_sref_system,\n          round(st_x(st_centroid(reduce_precision(coalesce(s.geom, l.centroid_geom), o.confidential, GREATEST(o.sensitivity_precision, s.privacy_precision, {$size}), s.entered_sref_system)))) as x,\n          round(st_y(st_centroid(reduce_precision(coalesce(s.geom, l.centroid_geom), o.confidential, GREATEST(o.sensitivity_precision, s.privacy_precision, {$size}), s.entered_sref_system)))) as y\n        FROM samples s\n        JOIN occurrences o ON o.sample_id=s.id\n        LEFT JOIN locations l on l.id=s.location_id AND l.deleted=false\n        WHERE {$alias}.id IN ({$idlist})")->result_array(TRUE);
         $km = $size / 1000;
         foreach ($smpInfo as $s) {
             $existing = $db->query("SELECT id FROM map_squares WHERE x={$s->x} AND y={$s->y} AND size={$s->size}")->result_array(FALSE);
             if (count($existing) === 0) {
                 $qry = $db->query("INSERT INTO map_squares (geom, x, y, size)\n            VALUES (reduce_precision(st_geomfromtext('{$s->geom}', {$srid}), '{$s->confidential}', {$s->size}, '{$s->entered_sref_system}'), {$s->x}, {$s->y}, {$s->size})");
                 $msqId = $qry->insert_id();
             } else {
                 $msqId = $existing[0]['id'];
             }
             $db->query("UPDATE cache_occurrences co SET map_sq_{$km}km_id={$msqId} WHERE sample_id={$s->id}");
         }
     }
 }
Exemplo n.º 7
0
/**
 * Hook into the task scheduler. When run, the system checks the cache_occurrences table for records where the data cleaner has marked
 * the record as data_cleaner_info "pass", record_status="C", the system then sets the record to verified automatically.
 * @param string $last_run_date Date last run, or null if never run
 * @param object $db Database object.
 */
function auto_verify_scheduled_task($last_run_date, $db)
{
    $autoVerifyNullIdDiff = kohana::config('auto_verify.auto_accept_occurrences_with_null_id_difficulty');
    global $processOldData;
    $processOldData = kohana::config('auto_verify.process_old_data');
    if (empty($autoVerifyNullIdDiff)) {
        print_r("Unable to automatically verify occurrences when the auto_accept_occurrences_with_null_id_difficulty entry is empty.<br>");
        kohana::log('error', 'Unable to automatically verify occurrences when the auto_accept_occurrences_with_null_id_difficulty configuration entry is empty.');
        return false;
    }
    //Do we need to consider old data (probably as a one-off run) or just newly changed data.
    $subQuery = "\n    SELECT co.id";
    if (!empty($processOldData) && $processOldData === 'true') {
        $subQuery .= "  \n      FROM cache_occurrences co";
    } else {
        $subQuery .= "  \n      FROM occdelta od\n      JOIN cache_occurrences co on co.id=od.id";
    }
    $subQuery .= "\n    JOIN surveys s on s.id = co.survey_id AND s.auto_accept=true AND s.deleted=false\n    LEFT JOIN cache_taxon_searchterms cts on cts.taxon_meaning_id = co.taxon_meaning_id \n    WHERE co.data_cleaner_info='pass' AND co.record_status='C' AND co.record_substatus IS NULL\n        AND ((" . $autoVerifyNullIdDiff . "=false AND cts.identification_difficulty IS NOT NULL AND cts.identification_difficulty<=s.auto_accept_max_difficulty) \n        OR (" . $autoVerifyNullIdDiff . "=true AND (cts.identification_difficulty IS NULL OR cts.identification_difficulty<=s.auto_accept_max_difficulty)))";
    $verificationTime = gmdate("Y\\/m\\/d H:i:s");
    //Need to update cache_occurrences, as this table has already been built at this point.
    $query = "\n    INSERT INTO occurrence_comments (comment, generated_by, occurrence_id,record_status,record_substatus,created_by_id,updated_by_id,created_on,updated_on,auto_generated)\n    SELECT 'Accepted based on automatic checks', 'system', id,'V','2',1,1,'" . $verificationTime . "','" . $verificationTime . "',true\n    FROM occurrences\n    WHERE id in\n    (" . $subQuery . ");\n      \n    UPDATE occurrences\n    SET \n    record_status='V',\n    record_substatus='2',\n    release_status='R',\n    verified_by_id=1,\n    verified_on='" . $verificationTime . "',\n    record_decision_source='M'\n    WHERE id in\n    (" . $subQuery . ");\n      \n    UPDATE cache_occurrences\n    SET \n    record_status='V',\n    record_substatus='2',\n    release_status='R',\n    verified_on='" . $verificationTime . "',\n    verifier='admin, core'\n    WHERE id in\n    (" . $subQuery . ");";
    $results = $db->query($query)->result_array(false);
    //Query to return count of records, as I was unable to pursuade the above query to output the number of updated
    //records correctly.
    $query = "\n    SELECT count(id)\n    FROM cache_occurrences co\n    WHERE co.verified_on='" . $verificationTime . "';";
    $results = $db->query($query)->result_array(false);
    if (!empty($results[0]['count']) && $results[0]['count'] > 1) {
        echo $results[0]['count'] . ' occurrence records have been automatically verified.</br>';
    } elseif (!empty($results[0]['count']) && $results[0]['count'] === "1") {
        echo '1 occurrence record has been automatically verified.</br>';
    } else {
        echo 'No occurrence records have been auto-verified.</br>';
    }
}
Exemplo n.º 8
0
 public static function importConfigRoutes()
 {
     $outboundPatterns = kohana::config('simpleroute.outbound_patterns');
     if (!is_array($outboundPatterns)) {
         return;
     }
     // This is the second work arround for the double loading issue... hmmm
     $createdPatterns = array();
     $simpleRoutes = array();
     foreach ($outboundPatterns as $outboundPattern) {
         if (empty($outboundPattern['name'])) {
             continue;
         }
         if (in_array($outboundPattern['name'], $createdPatterns)) {
             continue;
         }
         $createdPatterns[] = $outboundPattern['name'];
         if (empty($outboundPattern['patterns'])) {
             continue;
         }
         if (!is_array($outboundPattern['patterns'])) {
             $outboundPattern['patterns'] = array($outboundPattern['patterns']);
         }
         $simpleRoute =& $simpleRoutes[];
         $simpleRoute['name'] = $outboundPattern['name'];
         $simpleRoute['patterns'] = $outboundPattern['patterns'];
     }
     return $simpleRoutes;
 }
Exemplo n.º 9
0
 /**
  * Hook to prepare the database connection. Performs 2 tasks.
  *   1) Initialises the search path, unless configured not to do this (e.g. if this is set at db level).
  *   2) If this is a report request, sets the connection to read only.
  */
 public static function prepare_connection()
 {
     $uri = URI::instance();
     // we havent to proceed futher if a setup call was made
     if ($uri->segment(1) == 'setup_check') {
         return;
     }
     // continue to init the system
     //
     // add schema to the search path
     //
     $_schema = Kohana::config('database.default.schema');
     $query = '';
     if (!empty($_schema) && kohana::config('indicia.apply_schema') !== false) {
         $query = "SET search_path TO {$_schema}, public, pg_catalog;\n";
     }
     // Force a read only connection for reporting.
     if ($uri->segment(1) == 'services' && $uri->segment(2) == 'report') {
         $query .= "SET default_transaction_read_only TO true;\n";
     }
     if (!empty($query)) {
         $db = Database::instance();
         $db->query($query);
     }
 }
Exemplo n.º 10
0
 /**
  * Sends an email alert
  *
  * @param Validation_Core $post
  * @param Alert_Model $alert
  * @return bool 
  */
 public static function _send_email_alert($post, $alert)
 {
     if (!$post instanceof Validation_Core and !$alert instanceof Alert_Model) {
         throw new Kohana_Exception('Invalid parameter types');
     }
     // Email Alerts, Confirmation Code
     $alert_email = $post->alert_email;
     $alert_code = text::random('alnum', 20);
     $settings = kohana::config('settings');
     $to = $alert_email;
     $from = array();
     $from[] = $settings['alerts_email'] ? $settings['alerts_email'] : $settings['site_email'];
     $from[] = $settings['site_name'];
     $subject = $settings['site_name'] . " " . Kohana::lang('alerts.verification_email_subject');
     $message = Kohana::lang('alerts.confirm_request') . url::site() . 'alerts/verify?c=' . $alert_code . "&e=" . $alert_email;
     if (email::send($to, $from, $subject, $message, TRUE) == 1) {
         $alert->alert_type = self::EMAIL_ALERT;
         $alert->alert_recipient = $alert_email;
         $alert->alert_code = $alert_code;
         if (isset($_SESSION['auth_user'])) {
             $alert->user_id = $_SESSION['auth_user']->id;
         }
         $alert->save();
         self::_add_categories($alert, $post);
         return TRUE;
     }
     return FALSE;
 }
Exemplo n.º 11
0
 /**
  * Controller method for the import_progress path. Displays the upload template with 
  * progress bar and status message, which then initiates the actual import.
  */
 public function import_progress()
 {
     if (file_exists(kohana::config('upload.directory') . '/' . $_GET['file'])) {
         $this->template->content = new View('taxon_designation/upload');
         $this->template->title = 'Uploading designations';
     }
 }
Exemplo n.º 12
0
 public function __construct()
 {
     // Hook into routing, but not if running unit tests
     if (!in_array(MODPATH . 'phpUnit', kohana::config('config.modules'))) {
         Event::add('system.routing', array($this, 'check'));
     }
 }
Exemplo n.º 13
0
 public static function createExtension()
 {
     Event::$data += array('voicemail_password' => self::generatePin(), 'voicemail_timezone' => kohana::config('locale.timezone'), 'voicemail_email_all_messages' => empty(Event::$data['user']['email_address']) ? 0 : 1, 'voicemail_delete_file' => 0, 'voicemail_attach_audio_file' => 1, 'voicemail_email_address' => empty(Event::$data['user']['email_address']) ? '' : Event::$data['user']['email_address']);
     extract(Event::$data);
     Doctrine::getTable('Voicemail')->getRecordListener()->get('MultiTenant')->setOption('disabled', TRUE);
     $name_append = '';
     if (!empty($owner_name)) {
         $name_append = ' for ' . $owner_name;
     }
     try {
         $voicemail = new Voicemail();
         $voicemail['name'] = 'VM ' . $extension . $name_append;
         $voicemail['mailbox'] = $extension;
         $voicemail['password'] = $voicemail_password;
         $voicemail['account_id'] = $account_id;
         $voicemail['plugins'] = array('timezone' => array('timezone' => $voicemail_timezone));
         $voicemail['registry'] = array('email_all_messages' => $voicemail_email_all_messages, 'delete_file' => $voicemail_delete_file, 'attach_audio_file' => $voicemail_attach_audio_file, 'email_address' => $voicemail_email_address);
         $voicemail->save();
         $plugin = array('voicemail' => array('mwi_box' => $voicemail['voicemail_id']));
         $device['plugins'] = arr::merge($device['plugins'], $plugin);
     } catch (Exception $e) {
         Doctrine::getTable('Voicemail')->getRecordListener()->get('MultiTenant')->setOption('disabled', FALSE);
         kohana::log('error', 'Unable to generate voicemail for device: ' . $e->getMessage());
         throw $e;
     }
     Doctrine::getTable('Voicemail')->getRecordListener()->get('MultiTenant')->setOption('disabled', FALSE);
 }
Exemplo n.º 14
0
 /**
  * If not in the setup pages, but the indicia config file is missing, go to system setup.
  */
 public static function _setup_check()
 {
     $uri = URI::instance();
     $isOk = $uri->segment(1) == 'setup' || $uri->segment(1) == 'setup_check' || kohana::config('indicia.private_key', false, false) !== null;
     if (!$isOk) {
         url::redirect('setup_check');
     }
 }
Exemplo n.º 15
0
 public function index()
 {
     $db = new Database();
     $incidents = $db->query("SELECT incident.id, incident_title, \n\t\t\t\t\t\t\t\t incident_description, incident_verified, \n\t\t\t\t\t\t\t\t location.latitude, location.longitude, alert_sent.incident_id\n\t\t\t\t\t\t\t\t FROM incident INNER JOIN location ON incident.location_id = location.id\n\t\t\t\t\t\t\t\t LEFT OUTER JOIN alert_sent ON incident.id = alert_sent.incident_id");
     $config = kohana::config('alerts');
     $sms_from = NULL;
     $settings = ORM::factory('settings', 1);
     if ($settings->loaded == true) {
         // Get SMS Numbers
         if (!empty($settings->sms_no3)) {
             $sms_from = $settings->sms_no3;
         } elseif (!empty($settings->sms_no2)) {
             $sms_from = $settings->sms_no2;
         } elseif (!empty($settings->sms_no1)) {
             $sms_from = $settings->sms_no1;
         } else {
             $sms_from = "000";
         }
         // User needs to set up an SMS number
     }
     foreach ($incidents as $incident) {
         if ($incident->incident_id != NULL) {
             continue;
         }
         $verified = (int) $incident->incident_verified;
         if ($verified) {
             $latitude = (double) $incident->latitude;
             $longitude = (double) $incident->longitude;
             $proximity = new Proximity($latitude, $longitude);
             $alertees = $this->_get_alertees($proximity);
             foreach ($alertees as $alertee) {
                 $alert_type = (int) $alertee->alert_type;
                 if ($alert_type == 1) {
                     $sms = new Eflyer();
                     $sms->user = $settings->eflyer_username;
                     $sms->password = $settings->eflyer_password;
                     $sms->use_ssl = false;
                     $sms->sms();
                     $message = $incident->incident_description;
                     if ($sms->send($alertee->alert_recipient, $message) == "OK") {
                         $db->insert('alert_sent', array('alert_id' => $alertee->id, 'incident_id' => $incident->id, 'alert_date' => date("Y-m-d H:i:s")));
                         $db->clear_cache(true);
                     }
                 } elseif ($alert_type == 2) {
                     $to = $alertee->alert_recipient;
                     $from = $config['alerts_email'];
                     $subject = $incident->incident_title;
                     $message = $incident->incident_description;
                     if (email::send($to, $from, $subject, $message, TRUE) == 1) {
                         $db->insert('alert_sent', array('alert_id' => $alertee->id, 'incident_id' => $incident->id, 'alert_date' => date("Y-m-d H:i:s")));
                         $db->clear_cache(true);
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 16
0
 protected function get_ldap()
 {
     if (IN_DEV_MODE && kohana::config('workermgmt.use_mock_ldap')) {
         $ldap = new Mock_Ldap(kohana::config('workermgmt'), $this->ldap_credentials());
     } else {
         $ldap = new Ldap(kohana::config('workermgmt'), $this->ldap_credentials());
     }
     return $ldap;
 }
Exemplo n.º 17
0
 public static function conditionalTrigger()
 {
     if (!kohana::config('maintenance.on_requests', FALSE)) {
         return;
     }
     $maintenance_event = Doctrine::getTable('MaintenanceEvent')->find('1');
     if (!$maintenance_event) {
         return self::trigger();
     }
     $elapsed = time() - $maintenance_event['last_run'];
     if ($elapsed > kohana::config('maintenance.cycle_time', 300)) {
         self::trigger();
     }
 }
Exemplo n.º 18
0
 public static function getOutboundPattern($index, $engine = 'freeswitch')
 {
     // get the outbound patterns out of the config
     $outboundPatterns = kohana::config('simpleroute.outbound_patterns');
     // see if we have a definition for this
     if (!array_key_exists($index, $outboundPatterns)) {
         return FALSE;
     }
     if (empty($outboundPatterns[$index]['patterns'])) {
         return FALSE;
     }
     $patterns = $outboundPatterns[$index]['patterns'];
     if (!is_array($patterns)) {
         $patterns = array($patterns);
     }
     // based on the requesting engine generate the pattern required
     switch (strtolower($engine)) {
         case 'freeswitch':
             // Loop each rule and build a regex
             $pattern = '';
             foreach ($patterns as $rule) {
                 $rule = self::npaToRegex($rule);
                 if (empty($rule)) {
                     continue;
                 }
                 // Convert the short hand into regex
                 $pattern .= '^' . $rule . '$|';
             }
             // we added a pipe on the end of every rule so remove the last one
             //$pattern = str_replace(array('{', '}'), array('\{', '\}'), $pattern);
             return rtrim($pattern, '|');
         case 'asterisk':
             // Loop each rule and build a regex
             $pattern = array();
             foreach ($patterns as $rule) {
                 $rule = self::npaToAsteriskShort($rule);
                 if (empty($rule)) {
                     continue;
                 }
                 // Convert the short hand into regex
                 $pattern += $rule;
             }
             // because of the asterisk restrictions we return an array of
             // patterns that make up the regex groups in freeswitch
             return $pattern;
         default:
             return FALSE;
     }
 }
Exemplo n.º 19
0
 /**
  * Validates an array for a matching password and password_confirm field.
  *
  * @param  array    values to check
  * @param  string   save the user if
  * @return boolean
  */
 public function change_password(array &$array, $save = FALSE)
 {
     $array = Validation::factory($array)->pre_filter('trim')->add_rules('password', 'required', 'length[' . kohana::config('auth.password_length') . ']')->add_rules('password_confirm', 'matches[password]');
     if ($status = $array->validate()) {
         // Change the password
         $this->password = $array['password'];
         if ($save !== FALSE and $status = $this->save()) {
             if (is_string($save)) {
                 // Redirect to the success page
                 url::redirect($save);
             }
         }
     }
     return $status;
 }
Exemplo n.º 20
0
 /**
  * 根据注册项信息生成相应的html代码
  * @param $user_profile array  注册项信息
  * @param $class  string  css属性
  * return string
  */
 public static function show_view($user_attribute, $class = array())
 {
     empty($class) && ($class = array('text' => '', 'select' => '', 'radio' => '', 'checkbox' => ''));
     $type = kohana::config('user_attribute_type.attribute.' . $user_attribute['attribute_type'] . '.form');
     $html = '';
     if (!is_array($type) && !empty($type)) {
         switch ($type) {
             case 'text':
                 $attribute_type_arr = explode('.', $user_attribute['attribute_type']);
                 if ($attribute_type_arr[0] == 'time') {
                     $html .= '<input type="' . $type . '" name="' . $user_attribute['attribute_type'] . '"  readonly="true" class="' . $class[$type] . '" value="日期选择器"/>';
                 } else {
                     if ($attribute_type_arr[0] == 'input') {
                         $html .= '<input type="' . $type . '" name="' . $user_attribute['attribute_type'] . '"  readonly="true" class="' . $class[$type] . '"/>';
                     } else {
                         $html .= '<input type="' . $type . '" name="' . $user_attribute['attribute_type'] . '"  readonly="true" class="' . $class[$type] . '"/>';
                     }
                 }
                 break;
             case 'select':
                 $attribute_options = explode(',', trim($user_attribute['attribute_option'], ','));
                 $html .= '<select name="' . $user_attribute['attribute_type'] . '"  class="' . $class[$type] . '">';
                 foreach ($attribute_options as $attribute_option) {
                     $html .= '<option value="' . $attribute_option . '">' . $attribute_option . '</option>';
                 }
                 $html .= "</select>";
                 break;
             case 'radio':
                 $attribute_options = explode(',', trim($user_attribute['attribute_option'], ','));
                 foreach ($attribute_options as $attribute_option) {
                     $html .= $attribute_option . ' <input type="' . $type . '" name="' . $user_attribute['attribute_type'] . '" value="' . $attribute_option . '" class="' . $class[$type] . '"/> ';
                 }
                 break;
             case 'checkbox':
                 $attribute_options = explode(',', trim($user_attribute['attribute_option'], ','));
                 foreach ($attribute_options as $attribute_option) {
                     $html .= $attribute_option . '<input type="' . $type . '" name="' . $user_attribute['attribute_type'] . '[]" value="' . $attribute_option . '" class="' . $class[$type] . '"/>';
                 }
                 break;
             default:
                 break;
         }
     } else {
         $html = '';
     }
     return $html;
 }
Exemplo n.º 21
0
 /**
  * Action called when an formal upgrade is required.
  */
 public function upgrade()
 {
     $upgrader = new Upgrade_Model();
     try {
         $view = new View('upgrade');
         $this->template->title = 'Indicia Upgrade';
         $upgrader->run();
     } catch (Exception $e) {
         $view->error = $e->getMessage();
     }
     $system = new System_Model();
     $view->db_version = $system->getVersion();
     $view->app_version = kohana::config('version.version');
     $view->pgUserScriptsToBeApplied = $upgrader->pgUserScriptsToBeApplied;
     $view->slowScriptsToBeApplied = $upgrader->slowScriptsToBeApplied;
     $this->template->content = $view;
 }
/** 
 * Postprocessing for building a geom from the list of grid squares to make an SQL based check easy
 */
function data_cleaner_without_polygon_data_cleaner_postprocess($id, $db)
{
    $db->query('create temporary table geoms_without_polygon (geom geometry)');
    try {
        $r = $db->select('key, header_name')->from('verification_rule_data')->where('verification_rule_id', $id)->in('header_name', array('10km_GB', '10km_Ireland', '1km_GB', '1km_Ireland', '10km_CI', '1km_CI'))->get()->result();
        $wktList = array();
        foreach ($r as $gridSquare) {
            switch ($gridSquare->header_name) {
                case '10km_GB':
                case '1km_GB':
                    $system = 'osgb';
                    break;
                case '10km_Ireland':
                case '1km_Ireland':
                    $system = 'osie';
                    break;
                case '10km_CI':
                case '1km_CI':
                    $system = 'utm30ed50';
                    break;
                default:
                    continue;
                    // we don't know this grid square type - should not have come back from the query
            }
            $srid = kohana::config('sref_notations.internal_srid');
            try {
                $wktList[] = "(st_geomfromtext('" . spatial_ref::sref_to_internal_wkt($gridSquare->key, $system) . "', {$srid}))";
            } catch (Exception $e) {
                kohana::debug('alert', 'Did not import grid square ' . $gridSquare->key . " for rule {$id}");
                error::log_error('Importing without polygon rules', $e);
            }
        }
        if (!empty($wktList)) {
            $db->query("insert into geoms_without_polygon values " . implode(',', $wktList));
        }
        $date = date("Ymd H:i:s");
        $uid = $_SESSION['auth_user']->id;
        $db->query("delete from verification_rule_data where verification_rule_id={$id} and header_name='geom'");
        $db->query('insert into verification_rule_data (verification_rule_id, header_name, data_group, key, value, value_geom, created_on, created_by_id, updated_on, updated_by_id) ' . "select {$id}, 'geom', 1, 'geom', '-', st_union(geom), '{$date}', {$uid}, '{$date}', {$uid} from geoms_without_polygon");
        $db->query('drop table geoms_without_polygon');
    } catch (Exception $e) {
        $db->query('drop table geoms_without_polygon');
        throw $e;
    }
}
Exemplo n.º 23
0
 /**
  * When an image file is uploaded, the indicia configuration file is used to determine what resized
  * versions of the file must also be created. This method creates those files and applies the relevant
  * image manipulations.
  * @param string $uploadpath Path to the upload directory.
  * @param string $filename The file name of the original uploaded file.
  * @param string $subdir The subdirectory to save the image into
  * @param int $website_id The website's ID, which allows custom sizing for saved images on a per-website basis.
  */
 public static function create_image_files($uploadpath, $filename, $subdir = "", $website_id = null)
 {
     // First check that the configured graphics library is available.
     // @todo Consider implementing checks if the driver is set to ImageMagick or GraphicsMagick.
     if (kohana::config('image.driver') != 'GD' || function_exists('gd_info')) {
         // tolerate path with or withoug trailing slash
         if (substr($uploadpath, -1) != '\\' && substr($uploadpath, -1) != '/') {
             $uploadpath = $uploadpath . '/';
         }
         if ($subdir != "" && substr($subdir, -1) != '\\' && substr($subdir, -1) != '/') {
             $subdir = $subdir . '/';
         }
         $fileParts = explode('.', $filename);
         $ext = strtolower(array_pop($fileParts));
         if (in_array($ext, Image::$allowed_types)) {
             // website specific config available?
             $config = $website_id ? kohana::config('indicia.image_handling_website_' . $website_id) : false;
             // if not, is there a default config setting
             if (!$config) {
                 $config = kohana::config('indicia.image_handling');
             }
             // If no file based settings at all, then we just use a hard coded default.
             if (!$config) {
                 $config = array('thumb' => array('width' => 100, 'height' => 100, 'crop' => true), 'med' => array('width' => 500), 'default' => array('width' => 1024, 'upscale' => false));
             }
             foreach ($config as $imageName => $settings) {
                 $img = new Image($uploadpath . $subdir . $filename);
                 self::do_img_resize($img, $settings);
                 // Create the correct image path as image name + '-' + destination file name. Default image setting
                 // however is used to overwrite the original image.
                 if ($imageName == 'default') {
                     $imagePath = $uploadpath . $subdir . $filename;
                 } else {
                     if ($subdir != "" && !is_dir($uploadpath . $imageName . '-' . $subdir)) {
                         kohana::log('debug', 'Creating Directory ' . $uploadpath . $imageName . '-' . $subdir);
                         mkdir($uploadpath . $imageName . '-' . $subdir, 0755, true);
                     }
                     $imagePath = $uploadpath . $imageName . '-' . $subdir . $filename;
                 }
                 $img->save($imagePath);
             }
         }
     }
 }
Exemplo n.º 24
0
 static function update_db($db)
 {
     // Check if the db is even assigned to anyone. This is a requirement.
     if (Mhi_Site_Database_Model::db_assigned($db) == false) {
         return false;
     }
     $mhi_db = Kohana::config('database.default');
     $table_prefix = $mhi_db['table_prefix'];
     $mhi_db_name = $mhi_db['connection']['database'];
     $settings = kohana::config('settings');
     $current_version = $settings['db_version'];
     // Switch to new DB for a moment
     mysql_query('USE ' . $db . ';');
     // START: Everything that happens in the deployment DB happens below
     $settings = ORM::factory('settings', 1);
     $db_version = $settings->db_version;
     $upgrade_to = $db_version + 1;
     // Check if we even need to apply this update
     if ($db_version >= $current_version) {
         mysql_query('USE ' . $mhi_db_name);
         return false;
     }
     // Check if the update script exists
     $upgrade_schema = @file_get_contents('sql/upgrade' . $db_version . '-' . $upgrade_to . '.sql');
     if ($upgrade_schema == false) {
         mysql_query('USE ' . $mhi_db_name);
         return false;
     }
     // If a table prefix is specified, add it to sql
     if ($table_prefix) {
         $find = array('CREATE TABLE IF NOT EXISTS `', 'INSERT INTO `', 'ALTER TABLE `', 'UPDATE `', 'DROP TABLE `');
         $replace = array('CREATE TABLE IF NOT EXISTS `' . $table_prefix . '_', 'INSERT INTO `' . $table_prefix . '_', 'ALTER TABLE `' . $table_prefix . '_', 'UPDATE `' . $table_prefix . '_', 'DROP TABLE `' . $table_prefix . '_');
         $upgrade_schema = str_replace($find, $replace, $upgrade_schema);
     }
     // Split by ; to get the sql statement for creating individual tables.
     $queries = explode(';', $upgrade_schema);
     //Put a custom mysql_query() here in case you want to run something outside of the sql files.
     foreach ($queries as $query) {
         $result = mysql_query($query);
     }
     // END: Everything that happens in the deployment DB happens above
     //Switch back to our db, otherwise we would be running off some other deployments DB and that wouldn't work
     mysql_query('USE ' . $mhi_db_name);
 }
Exemplo n.º 25
0
 public function __construct()
 {
     // AJAX requests don't need an outer template
     if (request::is_ajax()) {
         $this->template = 'templates/blank';
     }
     parent::__construct();
     // assign view array with system information
     //
     $this->template->system = Kohana::config_load('version');
     $this->db = Database::instance();
     $this->auth = new Auth();
     $this->session = new Session();
     if ($this->auth->logged_in()) {
         $this->template->menu = self::get_menu();
     }
     $title = kohana::config('indicia.warehouse_title');
     $this->template->warehouseTitle = $title ? $title : 'Indicia Warehouse';
 }
Exemplo n.º 26
0
 public function __construct($config = FALSE)
 {
     $this->production = false;
     //remark for test
     //$this->site_id = Mysite::instance()->id();
     $this->site_id = 1;
     if (!kohana::config('memcache.' . $config)) {
         $this->config = Kohana::config('memcache.default');
     } else {
         $this->config = kohana::config('memcache.' . $config);
     }
     if ($this->production) {
         // Initialize the drivers
         $this->server = new Memcache();
         foreach ($this->config['server'] as $item) {
             $this->server->addServer($item['host'], $item['port']) or die("cache error");
         }
     }
 }
Exemplo n.º 27
0
/**
 * Hook into the task scheduler. This uses the queries defined in the cache_builder.php
 * file to create and populate cache tables. The tables are not always up to date as they
 * are only updated when the scheduler runs, but they have the advantage of simplifying
 * the data model for reporting as well as reducing the need to join in queries, therefore
 * significantly improving report performance.
 * @param string $last_run_date Date last run, or null if never run
 * @param object $db Database object.
 */
function cache_builder_scheduled_task($last_run_date, $db)
{
    if (isset($_GET['force_cache_rebuild'])) {
        $last_run_date = date('Y-m-d', time() - 60 * 60 * 24 * 365 * 200);
    } elseif ($last_run_date === null) {
        // first run, so get all records changed in last day. Query will automatically gradually pick up the rest.
        $last_run_date = date('Y-m-d', time() - 60 * 60 * 24);
    }
    try {
        foreach (kohana::config('cache_builder') as $table => $queries) {
            cache_builder::populate_cache_table($db, $table, $last_run_date);
            if (!variable::get("populated-{$table}")) {
                // don't bother populating the next table, as there can be dependencies.
                break;
            }
        }
    } catch (Exception $e) {
        echo $e->getMessage();
    }
}
Exemplo n.º 28
0
function species_alerts_create_notifications($newOccDataForSpeciesAlert)
{
    $notificationCounter = 0;
    //For any new occurrence record which has a matching species alert record, we need to generate a notification for the user
    foreach ($newOccDataForSpeciesAlert as $speciesAlertOccurrenceData) {
        if ($speciesAlertOccurrenceData['record_status'] == 'V' && $speciesAlertOccurrenceData['cud'] == 'U') {
            $action = 'verified';
        } elseif ($speciesAlertOccurrenceData['cud'] == 'C') {
            $action = 'entered';
        } else {
            continue;
        }
        $sref = $speciesAlertOccurrenceData['entered_sref'];
        if (empty($sref)) {
            $sref = '*sensitive*';
        }
        $commentText = "A record of {$speciesAlertOccurrenceData['taxon']} at {$sref} on " . date("Y\\/m\\/d", strtotime($speciesAlertOccurrenceData['created_on'])) . " has been {$action}.<br\\/>";
        try {
            $from = kohana::config('species_alerts.from');
        } catch (Exception $e) {
            $from = 'system';
        }
        $notificationObj = ORM::factory('notification');
        $notificationObj->source = 'species alerts';
        $notificationObj->acknowledged = 'false';
        $notificationObj->triggered_on = date("Ymd H:i:s");
        $notificationObj->user_id = $speciesAlertOccurrenceData['alerted_user_id'];
        $notificationObj->source_type = 'S';
        $notificationObj->linked_id = $speciesAlertOccurrenceData['occurrence_id'];
        $notificationObj->data = json_encode(array('username' => $from, 'occurrence_id' => $speciesAlertOccurrenceData['occurrence_id'], 'comment' => $commentText, 'taxon' => $speciesAlertOccurrenceData['taxon'], 'date' => date("Y\\/m\\/d", strtotime($speciesAlertOccurrenceData['created_on'])), 'entered_sref' => $speciesAlertOccurrenceData['entered_sref'], 'auto_generated' => 't', 'record_status' => $speciesAlertOccurrenceData['record_status'], 'updated on' => date("Y-m-d H:i:s", strtotime($speciesAlertOccurrenceData['updated_on']))));
        $notificationObj->save();
        $notificationCounter++;
    }
    if ($notificationCounter == 0) {
        echo 'No new Species Alert notifications have been created.</br>';
    } elseif ($notificationCounter == 1) {
        echo '1 new Species Alert notification has been created.</br>';
    } else {
        echo $notificationCounter . ' new Species Alert notifications have been created.</br>';
    }
}
Exemplo n.º 29
0
 public static function notify_admins($message)
 {
     // Don't show the exceptions for this operation to the user. Log them
     // instead
     try {
         $settings = kohana::config('settings');
         $from = $settings['site_email'];
         $subject = $settings['site_name'] . "\n\t\t\t\t" . Kohana::lang('users.notification');
         $users = ORM::factory('user')->where('notify', 1)->find_all();
         foreach ($users as $user) {
             if ($user->has(ORM::factory('role', 'admin'))) {
                 $address = $user->email;
                 if (!email::send($address, $from, $subject, $message, TRUE)) {
                     Kohana::log('error', "email to {$address} could not be sent");
                 }
             }
         }
     } catch (Exception $e) {
         Kohana::log('error', "An exception occured " . $e->__toString());
     }
 }
Exemplo n.º 30
0
 /**
  * Do upgrade. Throws exception if upgrade fails.   
  */
 public function run()
 {
     $cache = Cache::instance();
     // delete the system table schema data from the cache, as we need to ensure we are not testing against a copy saved during a failed install attempt.
     $cache->delete('list_fieldssystem');
     $system = ORM::Factory('system');
     // Need to ensure system table has a last_run_script. It was not in the original
     // update process pre v0.8, but is required for 0.8 and later. As it is part of the upgrade
     // process it makes sense to add this here rather than via a script.
     if (!array_key_exists('last_run_script', $system->as_array())) {
         $this->db->query('ALTER TABLE system ADD last_run_script VARCHAR(500) null');
     }
     // version in the file system
     $new_version = kohana::config('version.version');
     // version in the database
     $old_version = $system->getVersion();
     // Downgrade not possible if the new version is lower than the database version
     if (1 == version_compare($old_version, $new_version)) {
         Kohana::log('error', "Current application version ({$new_version}) is lower than the database version ({$old_version}). Downgrade not possible.");
         return Kohana::lang('setup.error_downgrade_not_possible');
     }
     // This upgrade process was only introduced in version 0.2.3
     if (1 == version_compare('0.2.3', $old_version)) {
         $old_version = '0.2.3';
     }
     $last_run_script = $system->getLastRunScript('Indicia');
     $this->applyUpdateScripts($this->base_dir . "/modules/indicia_setup/", 'Indicia', $old_version, $last_run_script);
     // need to look for any module with a db folder, then read its system version and apply the updates.
     foreach (Kohana::config('config.modules') as $path) {
         // skip the indicia_setup module db files since they are for the main app
         if (basename($path) !== 'indicia_setup' && file_exists("{$path}/db/")) {
             $old_version = $system->getVersion(basename($path));
             $last_run_script = $system->getLastRunScript(basename($path));
             $this->applyUpdateScripts("{$path}/", basename($path), $old_version, $last_run_script);
         }
     }
     // In case the upgrade involves changes to supported spatial systems...
     $this->populate_spatial_systems_table();
 }