Пример #1
0
 /**
  * Sube la información en la categoria indicada
  *
  * @param array $datos Los datos recibitos por POST
  * @param string $categoria Categoria a la cual pertenece el envio
  * @return int  Retorna el ID del envio si hubo exito, sino retorna 0 o FALSE
  */
 public function subir(array $datos, $categoria)
 {
     $exito = FALSE;
     $categoria_id = ORM::factory("categoria")->where("nombre", "=", $categoria)->find()->id;
     // Si la categoria no existe en la base de datos sale con error
     if (!$categoria_id) {
         return FALSE;
     }
     // Hace la validacion
     if ($this->values($datos)->check()) {
         // Concatenamos los datos de las Actividades
         if ($categoria == "Actividades") {
             $pre = "<b>Lugar:</b> " . $datos['lugar'] . "<br>\n\t\t\t<b>Fecha:</b> " . $datos['fecha'] . "<br>\n\t\t\t<b>Hora:</b> " . $datos['hora'] . "<br><br>\n\t\t    ";
             $this->contenido = $pre . $datos['contenido'];
             echo kohana::debug($datos);
         }
         // Los datos han sido validados y los guardamos
         $this->save();
         // Guarda la relacion entre el envio y la categoria
         $contenido = ORM::factory("contenido");
         $contenido->envio_id = $this->id;
         // Obtiene el id de la categoria
         $contenido->categoria_id = $categoria_id;
         $contenido->save();
         $exito = $this->id;
     }
     // Llenamos los vectores con los valores que seran mostrados en los campos
     $this->errores = Arr::overwrite($this->errores, $this->validate()->errors(""));
     $this->formulario = Arr::overwrite($this->formulario, $datos);
     return $exito;
 }
Пример #2
0
 /** 
  * Test that a basic date out of range test works.
  */
 public function testDateOutOfRange()
 {
     // Need a test rule we can use to check it works
     $ruleArr = array('verification_rule:title' => 'test', 'verification_rule:test_type' => 'PeriodWithinYear', 'verification_rule:error_message' => 'test error', 'metaFields:metadata' => "Tvk=TESTKEY\nStartDate=0801\nEndDate=0831", 'metaFields:data' => "");
     $rule = ORM::Factory('verification_rule');
     $rule->set_submission_data($ruleArr, false);
     if (!$rule->submit()) {
         echo kohana::debug($rule->getAllErrors());
         throw new exception('Failed to create test rule');
     }
     try {
         $response = data_entry_helper::http_post($this->request, array('sample' => json_encode(array('sample:survey_id' => 1, 'sample:date' => '12/09/2012', 'sample:entered_sref' => 'SU1234', 'sample:entered_sref_system' => 'osgb')), 'occurrences' => json_encode(array(array('occurrence:taxa_taxon_list_id' => $this->ttl->id))), 'rule_types' => json_encode(array('PeriodWithinYear'))));
         $errors = json_decode($response['output'], true);
         $this->assertTrue(is_array($errors), 'Errors list not returned');
         $this->assertTrue(isset($errors[0]['taxa_taxon_list_id']) && $errors[0]['taxa_taxon_list_id'] === $this->ttl->id, 'Incorrect taxa_taxon_list_id returned');
         $this->assertTrue(isset($errors[0]['message']) && $errors[0]['message'] === 'test error', 'Incorrect message returned');
         foreach ($rule->verification_rule_metadata as $m) {
             $m->delete();
         }
         $rule->delete();
     } catch (Exception $e) {
         foreach ($rule->verification_rule_metadata as $m) {
             $m->delete();
         }
         $rule->delete();
     }
 }
Пример #3
0
 public function fetch_migrations()
 {
     try {
         $this->find_all();
     } catch (Database_Exception $a) {
         if ($a->getCode() == 1146) {
             //Tabla no existe
             echo kohana::debug($a->getMessage());
         }
     }
 }
Пример #4
0
 public function email()
 {
     include Kohana::find_file('vendor/mailchimp', 'MCAPI');
     $config = Kohana::config('mailchimp');
     $mailchimp = new MCAPI($config['apikey']);
     $owners = ORM::factory('owner')->find_all();
     foreach ($owners as $owner) {
         if (empty($owner->email)) {
             continue;
         }
         echo kohana::debug($mailchimp->listSubscribe($config['list_id'], $owner->email, '', 'text', false, true, true, false));
     }
     die('done');
 }
/** 
 * 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;
    }
}
Пример #6
0
 private function _get_from_FILES()
 {
     $validation = Validate::factory($_FILES, 'uploads');
     $validation->rule('file', 'upload::not_empty')->rule('file', 'upload::type', array(array('csv')));
     if ($validation->check()) {
         $this->hash = md5(time());
         Upload::save($_FILES['file'], $this->hash, sys_get_temp_dir());
     } else {
         foreach ($validation->errors() as $err) {
             switch ($err[0]) {
                 case 'upload::not_empty':
                     throw new Kohana_Exception('You did not choose a file to upload!');
                 case 'upload::type':
                     throw new Kohana_Exception('You can only import CSV files.');
                 default:
                     throw new Kohana_Exception('An error occured.<br />' . kohana::debug($err));
             }
         }
     }
 }
Пример #7
0
 /**
  * Builds a query to extract data from the requested entity, and also
  * include relationships to foreign key tables and the caption fields from those tables.
  * @param boolean $count if set to true then just returns a record count.
  * @todo Review this code for SQL Injection attack!
  * @todo Basic website filter done, but not clever enough.
  */
 protected function build_query_results($count = false)
 {
     $this->foreign_keys = array();
     $this->db->from($this->viewname);
     // Select all the table columns from the view
     if (!$count) {
         $fields = array_keys(postgreSQL::list_fields($this->viewname, $this->db));
         $usedFields = array();
         $request = array_merge($_GET, $_POST);
         $columns = isset($request['columns']) ? explode(',', $request['columns']) : false;
         foreach ($fields as &$field) {
             if (!$columns || in_array($field, $columns)) {
                 // geom binary data is no good to anyone. So convert to WKT.
                 if (preg_match('/^(.+_)?geom$/', $field)) {
                     $usedFields[] = 'st_astext(' . $this->viewname . ".{$field}) as {$field}";
                 } else {
                     $usedFields[] = $this->viewname . '.' . $field;
                 }
             }
         }
         $select = implode(', ', $usedFields);
         $this->db->select($select);
     }
     // If not in the warehouse, then the entity must explicitly allow full access, or contain a website ID to filter on.
     if (!$this->in_warehouse && !array_key_exists('website_id', $this->view_columns) && !array_key_exists('from_website_id', $this->view_columns) && !in_array($this->entity, $this->allow_full_access)) {
         // If access is from remote website, then either table allows full access or exposes a website ID to filter on.
         Kohana::log('info', $this->viewname . ' does not have a website_id - access denied');
         throw new EntityAccessError('No access to entity ' . $this->entity . ' allowed through view ' . $this->viewname, 1004);
     }
     if (array_key_exists('website_id', $this->view_columns)) {
         $websiteFilterField = 'website_id';
     } elseif (array_key_exists('from_website_id', $this->view_columns)) {
         $websiteFilterField = 'from_website_id';
     }
     // Loading a list of records (no record ID argument)
     if (isset($websiteFilterField)) {
         // we have a filter on website_id to apply
         if ($this->website_id) {
             // check if a request for shared data is being made. Also check this is valid to prevent injection.
             if (isset($_REQUEST['sharing']) && preg_match('/[reporting|peer_review|verification|data_flow|moderation]/', $_REQUEST['sharing'])) {
                 // request specifies the sharing mode (i.e. the task being performed, such as verification, moderation). So
                 // we can use this to work out access to other website data.
                 $this->db->join('index_websites_website_agreements as iwwa', array('iwwa.from_website_id' => $this->viewname . '.' . $websiteFilterField, 'iwwa.provide_for_' . $_REQUEST['sharing'] . "='t'" => ''), NULL, 'LEFT');
                 $this->db->where('(' . $this->viewname . '.' . $websiteFilterField . ' IS NULL OR iwwa.to_website_id=' . $this->website_id . ')');
             } else {
                 $this->db->in($this->viewname . '.' . $websiteFilterField, array(null, $this->website_id));
             }
         } elseif ($this->in_warehouse && !$this->user_is_core_admin) {
             // User is on Warehouse, but not core admin, so do a filter to all their websites.
             $allowedWebsiteValues = array_merge($this->user_websites);
             $allowedWebsiteValues[] = null;
             $this->db->in('website_id', $allowedWebsiteValues);
         }
     }
     if ($this->uri->total_arguments() == 0) {
         // filter the list according to the parameters in the call
         $this->apply_get_parameters_to_db($count);
     } else {
         $this->db->where($this->viewname . '.id', $this->uri->argument(1));
     }
     try {
         if ($count) {
             return $this->db->count_records();
         } else {
             $r = $this->db->get()->result_array(FALSE);
             // If we got no record but asked for a specific one, check if this was a permissions issue?
             if (!count($r) && $this->uri->total_arguments() !== 0 && !$this->check_record_access($this->entity, $this->uri->argument(1), $this->website_id, isset($_REQUEST['sharing']) ? $_REQUEST['sharing'] : false)) {
                 Kohana::log('info', 'Attempt to access existing record failed - website_id ' . $this->website_id . ' does not match website for ' . $this->entity . ' id ' . $this->uri->argument(1));
                 throw new AuthorisationError('Attempt to access existing record failed - website_id ' . $this->website_id . ' does not match website for ' . $this->entity . ' id ' . $this->uri->argument(1), 1001);
             }
             return $r;
         }
     } catch (Exception $e) {
         kohana::log('error', 'Error occurred running the following query from a service request:');
         kohana::log('error', $e->getMessage());
         kohana::log('error', $this->db->last_query());
         kohana::log('error', 'Request detail:');
         kohana::log('error', $this->uri->string());
         kohana::log('error', kohana::debug($_REQUEST));
         throw $e;
     }
 }
Пример #8
0
 /**
  * Actually validate and submit the inner submission.
  *
  * @return int Id of the submitted record, or null if this failed.
  * @throws Exception On access denied to the website of an existing record.
  */
 protected function validateAndSubmit()
 {
     $return = null;
     $collapseVals = create_function('$arr', 'if (is_array($arr)) {
        return $arr["value"];
      } else {
        return $arr;
      }');
     // Flatten the array to one that can be validated
     $vArray = array_map($collapseVals, $this->submission['fields']);
     if (!empty($vArray['website_id']) && !empty(self::$authorisedWebsiteId) && $vArray['website_id'] !== self::$authorisedWebsiteId) {
         throw new Exception('Access to write to this website denied.', 2001);
     }
     // If we're editing an existing record, merge with the existing data.
     // NB id is 0, not null, when creating a new user
     if (array_key_exists('id', $vArray) && $vArray['id'] != null && $vArray['id'] != 0) {
         $this->find($vArray['id']);
         $thisValues = $this->as_array();
         unset($thisValues['updated_by_id']);
         unset($thisValues['updated_on']);
         // don't overwrite existing website_ids otherwise things like shared verification portals end up
         // grabbing records to their own website ID.
         if (!empty($thisValues['website_id']) && !empty($vArray['website_id'])) {
             unset($vArray['website_id']);
         }
         // If there are no changed fields between the current and new record, skip the metadata update.
         $exactMatches = array_intersect_assoc($thisValues, $vArray);
         // Allow for different ways of submitting bool. Don't want to trigger metadata updates if submitting 'on' instead of true
         // for example.
         foreach ($vArray as $key => $value) {
             if (isset($this->{$key}) && ($this->{$key} === 't' && ($value === 'on' || $value === 1) || $this->{$key} === 'f' && ($value === 'off' || $value === 0))) {
                 $exactMatches[$key] = $this->{$key};
             }
         }
         $fieldsWithValuesInSubmission = array_intersect_key($thisValues, $vArray);
         $this->wantToUpdateMetadata = count($exactMatches) !== count($fieldsWithValuesInSubmission);
         $vArray = array_merge($thisValues, $vArray);
         $this->existing = true;
     }
     Kohana::log("debug", "About to validate the following array in model " . $this->object_name);
     Kohana::log("debug", kohana::debug($this->sanitise($vArray)));
     try {
         if (array_key_exists('deleted', $vArray) && $vArray['deleted'] == 't') {
             // For a record deletion, we don't want to validate and save anything. Just mark delete it.
             $this->deleted = 't';
             $this->set_metadata();
             $v = $this->save();
         } else {
             // Create a new record by calling the validate method
             $v = $this->validate(new Validation($vArray), true);
         }
     } catch (Exception $e) {
         $v = false;
         $this->errors['general'] = $e->getMessage();
         error::log_error('Exception during validation', $e);
     }
     if ($v) {
         // Record has successfully validated so return the id.
         Kohana::log("debug", "Record " . $this->id . " has validated successfully");
         $return = $this->id;
     } else {
         // Errors.
         Kohana::log("debug", "Record did not validate");
         // Log more detailed information on why
         foreach ($this->errors as $f => $e) {
             Kohana::log("debug", "Field " . $f . ": " . $e);
         }
     }
     return $return;
 }
Пример #9
0
 public function tool()
 {
     if (empty($_GET['tool_id'])) {
         die('invalid tool_id');
     }
     $tool_id = valid::id_key($_GET['tool_id']);
     $tool = ORM::factory('tool', $tool_id);
     if (!$tool->loaded) {
         die('invalid tool');
     }
     $toolname = strtolower($tool->system_tool->name);
     # load the tool parent
     $parent = ORM::factory($toolname, $tool->parent_id);
     if (!$parent->loaded) {
         die('invalid parent table');
     }
     # build the object.
     $export = new stdClass();
     $export->name = $toolname;
     # export the parent table.
     $parent_table = new stdClass();
     foreach ($parent->table_columns as $key => $value) {
         $parent_table->{$key} = $parent->{$key};
     }
     $export->parent_table = $parent_table;
     # export any child tables.
     $child_tables = new stdClass();
     # loop through data from available child tables.
     foreach ($parent->has_many as $table_name) {
         $table_name = inflector::singular($table_name);
         $child_tables->{$table_name} = array();
         # get the child table model so we can iterate through the fields.
         $table = ORM::factory($table_name);
         # get any rows beloning to the parent.
         $rows = ORM::factory($table_name)->where(array('fk_site' => $this->site_id, "{$toolname}_id" => $parent->id))->find_all();
         foreach ($rows as $row) {
             $object = new stdClass();
             foreach ($table->table_columns as $key => $value) {
                 $object->{$key} = $row->{$key};
             }
             array_push($child_tables->{$table_name}, $object);
         }
     }
     $export->child_tables = $child_tables;
     # get the css file.
     $export->css = file_get_contents($this->assets->themes_dir("{$this->theme}/tools/{$toolname}/_created/{$parent->id}/{$parent->type}_{$parent->view}.css"));
     $json = json_encode($export);
     echo '<h2>Copy this exactly and place into the importer=)</h2>';
     echo "<textarea style='width:99%;height:400px;'>{$json}</textarea>";
     die;
     echo kohana::debug($export);
     die;
     # just testing ...
     echo self::import($json);
     die;
 }
 private function saveControlList($list, $blockId, $websiteId)
 {
     $weight = 0;
     foreach ($list as $control) {
         $changed = false;
         if (substr($control['id'], 0, 8) == 'control-') {
             $ctrlId = str_replace('control-', '', $control['id']);
             $model = ORM::factory($_GET['type'] . '_attributes_website', $ctrlId);
         } elseif (substr($control['id'], 0, 10) == 'attribute-') {
             $attrId = str_replace('attribute-', '', $control['id']);
             // get model for a new record
             $model = ORM::factory($_GET['type'] . '_attributes_website');
             $attrVar = $this->type . '_attribute_id';
             // link the model to the existing attribute we have the ID for
             $model->{$attrVar} = $attrId;
             $model->restrict_to_survey_id = $this->_survey_id;
             $model->website_id = $websiteId;
             $changed = true;
         } else {
             continue;
         }
         if ($model->weight != $weight) {
             $model->weight = $weight;
             $changed = true;
         }
         if ($model->form_structure_block_id != $blockId) {
             $model->form_structure_block_id = $blockId;
             $changed = true;
         }
         $weight++;
         if (isset($control['deleted']) && $control['deleted']) {
             // deleting, so existing control must be removed
             if (substr($control['id'], 0, 8) == 'control-') {
                 $model->delete();
             }
             $id = null;
         } elseif ($changed) {
             $model->set_metadata();
             $model->save();
             if (count($model->getAllErrors()) !== 0) {
                 throw new Exception(kohana::debug($model->getAllErrors()));
             }
         }
     }
 }
Пример #11
0
 private function update()
 {
     $sites = ORM::factory('site')->find_all();
     foreach ($sites as $site) {
         # $theme_dir = $this->assets->themes_dir();
         $theme_dir = DATAPATH . "{$site->subdomain}/themes";
         $themes = Jdirectory::contents($theme_dir, 'root', 'list_dir');
         foreach ($themes as $theme) {
             $tool_dir = "{$theme_dir}/{$theme}/tools";
             if (!is_dir($tool_dir)) {
                 continue;
             }
             $toolnames = Jdirectory::contents($tool_dir, 'root', 'list_dir');
             foreach ($toolnames as $toolname) {
                 $created = "{$theme_dir}/{$theme}/tools/{$toolname}/_created";
                 if (!is_dir($created)) {
                     continue;
                 }
                 $instances = Jdirectory::contents($created, 'root', 'list_dir');
                 foreach ($instances as $instance) {
                     $path = "{$theme_dir}/{$theme}/tools/{$toolname}/_created/{$instance}";
                     if (is_dir($path)) {
                         rename($path, "{$theme_dir}/{$theme}/tools/{$toolname}/{$instance}");
                     }
                 }
                 if (is_dir($created)) {
                     rmdir($created);
                 }
             }
         }
     }
     echo 'done';
     die;
     echo kohana::debug($themes);
     die;
 }
Пример #12
0
<dl>
	<dt>Kadldap::all_contacts()</dt>
	<dd><?php 
    echo kohana::debug($kadldap->all_contacts());
    ?>
</dd>
	<dt>all_distribution_groups</dt>
	<dd><?php 
    echo kohana::debug($kadldap->all_distribution_groups());
    ?>
</dd>
	<dt>get_account_suffix</dt>
	<dd><?php 
    echo kohana::debug($kadldap->get_account_suffix());
    ?>
</dd>
	<dt>Kadldap::user_info($username)</dt>
	<dd><?php 
    echo kohana::debug($kadldap->user_info(auth::instance()->get_user()));
    ?>
</dd>
	<dt>Kadldap::user_groups($username)</dt>
	<dd><?php 
    echo kohana::debug($kadldap->user_groups(auth::instance()->get_user()));
    ?>
</dd>
</dl>

<?php 
}
Пример #13
0
    /**
     * KMS method to output hard error messages to users
     * @param  string  error message
     * @param  mixed   optional arguments for debugging
     * @param  string  page title
     */
    public static function stop($message, $args = 'Passed in mixed arguments', $title = 'KMS Error', $debug = FALSE)
    {
        if ($args !== 'Passed in mixed arguments') {
            $message .= "\n<p>Arguments:</p>" . kohana::debug($args);
        }
        $message .= "\n<p><a href=\"javascript:history.back()\">&laquo; Back</a></p>";
        // header status
        if (isset($_SERVER['SERVER_PROTOCOL'])) {
            $protocol = $_SERVER['SERVER_PROTOCOL'];
        } else {
            $protocol = 'HTTP/1.1';
        }
        header($protocol . ' 500 Internal Server Error');
        ob_clean();
        ob_start();
        ?>
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml" <?php 
        if (function_exists('language_attributes')) {
            language_attributes();
        }
        ?>
>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title><?php 
        echo $title;
        ?>
</title>
		<link rel="stylesheet" href="css/install.css" type="text/css" />
		<?php 
        echo html::style('kms-asset/css/error.css');
        ?>
	</head>
	<body>
		<p><?php 
        echo $message;
        ?>
</p>
	</body>
	</html>
	<?php 
        $response = ob_get_clean();
        if ($debug === FALSE) {
            die($response);
        } else {
            return $response;
        }
    }