Ejemplo n.º 1
2
 public static function getAudioInfo($path)
 {
     if (!is_file($path)) {
         kohana::log('debug', 'Asked for audio info on non-existant file: "' . $path . '"');
         return FALSE;
     }
     $id3 = new getID3();
     $info = $id3->analyze($path);
     if (!empty($info['error'])) {
         kohana::log('debug', 'Unable to analyze "' . $path . '" because ' . implode(' - ', $info['error']));
         return FALSE;
     }
     switch ($info['audio']['dataformat']) {
         case 'wav':
             return array('type' => $info['audio']['dataformat'], 'compression' => number_format($info['audio']['compression_ratio'], 4), 'channels' => $info['audio']['channels'], 'rates' => $info['audio']['streams'][0]['sample_rate'], 'byterate' => $info['audio']['bitrate'], 'bits' => $info['audio']['bits_per_sample'], 'size' => $info['filesize'], 'length' => number_format($info['playtime_seconds'], 4));
         case 'mp1':
             return array('type' => $info['audio']['dataformat'], 'compression' => number_format($info['audio']['compression_ratio'], 4), 'channels' => $info['audio']['channels'], 'rates' => $info['audio']['streams'][0]['sample_rate'], 'byterate' => $info['audio']['bitrate'], 'bits' => $info['audio']['bits_per_sample'], 'size' => $info['filesize'], 'length' => number_format($info['playtime_seconds'], 4));
         case 'mp3':
             return array('type' => $info['audio']['dataformat'], 'compression' => number_format($info['audio']['compression_ratio'], 4), 'channels' => $info['audio']['channels'], 'rates' => $info['audio']['sample_rate'], 'byterate' => $info['audio']['bitrate'], 'bits' => NULL, 'size' => $info['filesize'], 'length' => number_format($info['playtime_seconds'], 4));
         case 'ogg':
             return array('type' => $info['audio']['dataformat'], 'compression' => number_format($info['audio']['compression_ratio'], 4), 'channels' => $info['audio']['channels'], 'rates' => $info['audio']['sample_rate'], 'byterate' => $info['audio']['bitrate'], 'bits' => NULL, 'size' => $info['filesize'], 'length' => number_format($info['playtime_seconds'], 4));
         default:
             kohana::log('error', 'Unhandled media type(' . $info['audio']['dataformat'] . ') for file ' . $path);
     }
     return FALSE;
 }
Ejemplo n.º 2
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);
     }
 }
Ejemplo n.º 3
0
 public static function register($driver, $hook)
 {
     $driverName = Telephony::getDriverName();
     if (!$driverName or $driverName == 'none') {
         return true;
     } elseif (!class_exists($driverName)) {
         Kohana::log('error', 'Telephony -> Unable to register the dialplan driver \'' . $driverName . '\'');
         return false;
     }
     $hookClass = $driverName . '_' . $driver . '_Driver';
     if (!class_exists($hookClass)) {
         Kohana::log('error', 'Telephony -> Unable to register the dialplan hook \'' . $driver . '\'(' . $hookClass . ')');
         return false;
     }
     if (empty(self::$dialplanSections)) {
         kohana::log('debug', 'Telephony -> EVAL ' . $driverName . '::getDialplanSections();');
         $sections = eval('return ' . $driverName . '::getDialplanSections();');
         if (is_array($sections)) {
             self::$dialplanSections = $sections;
         }
     }
     if (!in_array($hook, self::$dialplanSections)) {
         //Logger::ExceptionByCaller();
         throw new Exception('The hook ' . $hook . ' is not a recognized telephony global hook. (While trying to register callback ' . $driver . ')');
     }
     // Register event as _telephony.action with the callback array as the callback
     Event::add('_telephony.' . $hook, array($hookClass, $hook));
     Kohana::log('debug', 'Telephony -> Added hook for _telephony.' . $hook . ' to call ' . $hookClass . '::' . $hook);
     return TRUE;
 }
Ejemplo n.º 4
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);
     }
 }
Ejemplo n.º 5
0
 public static function echo_test()
 {
     $featureCode = new FeatureCode();
     $featureCode['name'] = 'Echo Test';
     $featureCode['registry'] = array('feature' => 'echo');
     $featureCode->save();
     try {
         $location = Doctrine::getTable('Location')->findAll();
         if (!$location->count()) {
             throw Exception('Could not find location id');
         }
         $location_id = arr::get($location, 0, 'location_id');
         $number = new Number();
         $number['user_id'] = users::getAttr('user_id');
         $number['number'] = '9999';
         $number['location_id'] = $location_id;
         $number['registry'] = array('ignoreFWD' => '0', 'ringtype' => 'ringing', 'timeout' => 20);
         $dialplan = array('terminate' => array('transfer' => 0, 'voicemail' => 0, 'action' => 'hangup'));
         $number['dialplan'] = $dialplan;
         $number['class_type'] = 'FeatureCodeNumber';
         $number['foreign_id'] = $featureCode['feature_code_id'];
         $context = Doctrine::getTable('Context')->findOneByName('Outbound Routes');
         $number['NumberContext']->fromArray(array(0 => array('context_id' => $context['context_id'])));
         $numberType = Doctrine::getTable('NumberType')->findOneByClass('FeatureCodeNumber');
         if (empty($numberType['number_type_id'])) {
             return FALSE;
         }
         $number['NumberPool']->fromArray(array(0 => array('number_type_id' => $numberType['number_type_id'])));
         $number->save();
         return $number['number_id'];
     } catch (Exception $e) {
         kohana::log('error', 'Unable to initialize device number: ' . $e->getMessage());
         throw $e;
     }
 }
Ejemplo n.º 6
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'));
     }
 }
Ejemplo n.º 7
0
 public function rename($id)
 {
     access::verify_csrf();
     $tag = ORM::factory("tag", $id);
     if (!$tag->loaded) {
         kohana::show_404();
     }
     $form = tag::get_rename_form($tag);
     $valid = $form->validate();
     if ($valid) {
         $new_name = $form->rename_tag->inputs["name"]->value;
         $new_tag = ORM::factory("tag")->where("name", $new_name)->find();
         if ($new_tag->loaded) {
             $form->rename_tag->inputs["name"]->add_error("in_use", 1);
             $valid = false;
         }
     }
     if ($valid) {
         $old_name = $tag->name;
         $tag->name = $new_name;
         $tag->save();
         $message = t("Renamed tag %old_name to %new_name", array("old_name" => $old_name, "new_name" => $tag->name));
         message::success($message);
         log::success("tags", $message);
         print json_encode(array("result" => "success", "location" => url::site("admin/tags"), "tag_id" => $tag->id, "new_tagname" => html::clean($tag->name)));
     } else {
         print json_encode(array("result" => "error", "form" => $form->__toString()));
     }
 }
Ejemplo n.º 8
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();
     }
 }
Ejemplo n.º 9
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);
 }
Ejemplo n.º 10
0
 public function rename($id)
 {
     access::verify_csrf();
     $tag = ORM::factory("tag", $id);
     if (!$tag->loaded) {
         kohana::show_404();
     }
     // Don't use a form as the form is dynamically created in the js
     $post = new Validation($_POST);
     $post->add_rules("name", "required", "length[1,64]");
     $valid = $post->validate();
     if ($valid) {
         $new_name = $this->input->post("name");
         $new_tag = ORM::factory("tag")->where("name", $new_name)->find();
         if ($new_tag->loaded) {
             $error_msg = t("There is already a tag with that name");
             $valid = false;
         }
     } else {
         $error_msg = $post->errors();
         $error_msg = $error_msg[0];
     }
     if ($valid) {
         $old_name = $tag->name;
         $tag->name = $new_name;
         $tag->save();
         $message = t("Renamed tag %old_name to %new_name", array("old_name" => $old_name, "new_name" => $tag->name));
         message::success($message);
         log::success("tags", $message);
         print json_encode(array("result" => "success", "location" => url::site("admin/tags"), "tag_id" => $tag->id, "new_tagname" => html::clean($tag->name)));
     } else {
         print json_encode(array("result" => "error", "message" => (string) $error_msg));
     }
 }
Ejemplo n.º 11
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';
 }
Ejemplo n.º 12
0
Archivo: fax.php Proyecto: swk/bluebox
 public function getDispositionForm()
 {
     $faxprof = Input::instance()->post('faxprofile');
     $faxdisp = Doctrine::getTable('FaxDisposition')->find($faxprof['fxp_fxd_id']);
     if ($faxdisp) {
         $packageobj = Doctrine::getTable('package')->find($faxdisp['fxd_package_id']);
         if ($packageobj) {
             try {
                 if (!($package = Package_Catalog::getInstalledPackage($packageobj->name))) {
                     echo 'Package not ' . $packageobj->name . ' found.';
                     exit;
                 }
                 $formfile = $package['directory'] . '/views/' . $packageobj->name . '/' . $faxdisp['fxd_name'] . '.php';
                 kohana::Log('debug', 'Looking for view ' . $formfile);
                 if (file_exists($formfile)) {
                     $featureFormView = new View($packageobj->name . '/' . $faxdisp['fxd_name']);
                     kohana::Log('debug', 'View file found.');
                     if (isset($faxprof['fxp_id']) && !empty($faxprof['fxp_id']) && $faxprof['fxp_id'] != '') {
                         $faxprofobj = Doctrine::getTable('FaxProfile')->find($faxprof['fxp_id']);
                     } else {
                         $faxprofobj = new FaxProfile();
                     }
                     $featureFormView->set_global('faxprofile', $faxprofobj);
                     echo $featureFormView->render(TRUE);
                 } else {
                     kohana::Log('debug', 'View file not found.');
                 }
             } catch (Package_Catalog_Exception $e) {
                 echo 'Package not ' . $packageobj->name . ' found.';
             }
         }
     }
     exit;
 }
Ejemplo n.º 13
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());
     }
 }
Ejemplo n.º 14
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;
 }
Ejemplo n.º 15
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;
 }
Ejemplo n.º 16
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;
 }
Ejemplo n.º 17
0
 public function before()
 {
     parent::before();
     $lang = $this->request->param('lang');
     // Make sure we have a valid language
     if (!in_array($lang, array_keys(Kohana::config('kohana')->languages))) {
         $this->request->action = 'error';
         throw new Kohana_Request_Exception('Unable to find a route to match the URI: :uri (specified language was not found in config)', array(':uri' => $this->request->uri));
     }
     I18n::$lang = $lang;
     if (isset($this->page_titles[$this->request->action])) {
         // Use the defined page title
         $title = $this->page_titles[$this->request->action];
     } else {
         // Use the page name as the title
         $title = ucwords(str_replace('_', ' ', $this->request->action));
     }
     $this->template->title = $title;
     if (!kohana::find_file('views', 'pages/' . $this->request->action)) {
         $this->request->action = 'error';
     }
     $this->template->content = View::factory('pages/' . $this->request->action);
     $this->template->set_global('request', $this->request);
     $this->template->meta_tags = array();
 }
Ejemplo n.º 18
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;
 }
Ejemplo n.º 19
0
 public function emailid($user_id)
 {
     // Display a form that a vistor can use to contact a registered user.
     // If this page is disabled, show a 404 error.
     if (module::get_var("contactowner", "contact_user_link") != true) {
         kohana::show_404();
     }
     // Locate the record for the user specified by $user_id,
     //   use this to determine the user's name.
     $userDetails = ORM::factory("user")->where("id", $user_id)->find_all();
     // Make a new form with a couple of text boxes.
     $form = new Forge("contactowner/sendemail", "", "post", array("id" => "gContactOwnerSendForm"));
     $sendmail_fields = $form->group("contactOwner");
     $sendmail_fields->input("email_to")->label(t("To:"))->value($userDetails[0]->name);
     $sendmail_fields->input("email_from")->label(t("From:"))->value(user::active()->email);
     $sendmail_fields->input("email_subject")->label(t("Subject:"))->value("");
     $sendmail_fields->textarea("email_body")->label(t("Message:"))->value("");
     $sendmail_fields->hidden("email_to_id")->value($user_id);
     // Add a save button to the form.
     $sendmail_fields->submit("SendMessage")->value(t("Send"));
     // Set up and display the actual page.
     $template = new Theme_View("page.html", "Contact");
     $template->content = new View("contactowner_emailform.html");
     $template->content->sendmail_form = $form;
     print $template;
 }
Ejemplo n.º 20
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;
 }
Ejemplo n.º 21
0
 private static function runEvents($eventName, &$data = NULL)
 {
     kohana::log('debug', 'Running event ' . $eventName);
     // Returns of the callbacks for event specified
     $events = Event::get($eventName);
     // Loop through each event, instantiate the event object, and call the event.
     // NOTE: We do this because we rely on __get/__set methods in bluebox plugins and they must be able to use $object->
     // to reference the current controller
     $return_value = TRUE;
     foreach ($events as $event) {
         // Share our current controller w/ the event system
         Event::$data =& $data;
         // Go get our plugin object
         $obj =& self::initialize($event[0]);
         if (method_exists($obj, $event[1])) {
             $return = call_user_func(array($obj, $event[1]));
             kohana::log('debug', 'Plugin hook ' . get_class($obj) . '::' . $event[1] . '() returned ' . ($return ? 'true' : 'false'));
             // If the func doesnt have a return or its not bool, assume true
             if (is_null($return) || !is_bool($return)) {
                 $return = TRUE;
             }
             // Bitwise AND of all the returns (if any returns false, the event will return false)
             $return_value = $return_value & $return;
         } else {
             throw new Exception('Tried to call plugin method ' . get_class($obj) . '::' . $event[1] . '(), but no such method exists. (Event ' . $eventName . ')');
         }
         // Do this to prevent data from getting 'stuck'
         $clearData = '';
         Event::$data =& $clearData;
     }
     return $return_value;
 }
Ejemplo n.º 22
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>';
    }
}
Ejemplo n.º 23
0
 public function action_login()
 {
     if ($this->_auth->logged_in()) {
         // redirect to the user account
         $this->request->redirect(Route::get('admin')->uri(), 200);
     }
     // Disable sidebars on login page
     $this->_sidebars = FALSE;
     $this->title = __('Sign In');
     $user = ORM::factory('user');
     // Create form action
     $destination = isset($_GET['destination']) ? $_GET['destination'] : 'admin';
     $params = array('action' => 'login');
     $action = Route::get('admin/login')->uri($params) . URL::query(array('destination' => $destination));
     if ($layout = kohana::find_file('views', 'layouts/login')) {
         $this->template->set_filename('layouts/login');
     }
     $view = View::factory('admin/login')->set('use_username', Config::get('auth.username'))->set('post', $user)->set('action', $action)->bind('errors', $this->_errors);
     if ($this->valid_post('login')) {
         try {
             // Check Auth
             $user->login($this->request->post());
             // If the post data validates using the rules setup in the user model
             Message::success(__('Welcome, %title!', array('%title' => $user->nick)));
             Log::info('User :name logged in.', array(':name' => $user->name));
             // redirect to the user account
             $this->request->redirect(isset($_GET['destination']) ? $_GET['destination'] : 'admin', 200);
         } catch (Validation_Exception $e) {
             $this->_errors = $e->array->errors('login', TRUE);
         }
     }
     $this->response->body($view);
 }
Ejemplo n.º 24
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}");
         }
     }
 }
Ejemplo n.º 25
0
 public function children()
 {
     if (!user::active()->admin) {
         access::forbidden();
     }
     $paths = unserialize(module::get_var("server_add", "authorized_paths"));
     $path_valid = false;
     $path = $this->input->post("path");
     $checked = $this->input->post("checked") == "true";
     foreach (array_keys($paths) as $valid_path) {
         if ($path_valid = strpos($path, $valid_path) === 0) {
             break;
         }
     }
     if (empty($path_valid)) {
         throw new Exception("@todo BAD_PATH");
     }
     if (!is_readable($path) || is_link($path)) {
         kohana::show_404();
     }
     $tree = new View("server_add_tree.html");
     $tree->data = $this->_get_children($path);
     $tree->checked = $checked;
     $tree->tree_id = "tree_" . md5($path);
     print $tree;
 }
Ejemplo n.º 26
0
 protected function pre_save(&$object)
 {
     $errors = array();
     libxml_use_internal_errors(TRUE);
     $cleaned = array();
     foreach ($object['registry'] as $section => $xml) {
         $dom = new DOMDocument('1.0');
         $dom->formatOutput = FALSE;
         if (strlen(trim($xml)) == 0) {
             kohana::log('debug', 'Section: ' . $section . ' Empty XML');
             unset($cleaned[$section]);
             continue;
         }
         try {
             if ($dom->loadXML('<root>' . trim($xml) . '</root>')) {
                 $cleaned[$section] = trim(str_replace('<?xml version="1.0"?>', '', $dom->saveXML()));
                 kohana::log('debug', 'Section: ' . $section . ' Cleaned XML: ' . $dom->saveXML());
                 continue;
             } else {
                 $errors[] = ucfirst($section);
             }
         } catch (Exception $e) {
             $errors[] = ucfirst($section);
         }
     }
     if (count($errors) > 0) {
         throw new Exception('Please correct the XML errors in these sections: ' . implode(', ', $errors));
     }
     $object['registry'] = $cleaned;
     kohana::log('debug', 'Successfully validated XML');
     parent::pre_save($object);
 }
Ejemplo n.º 27
0
 public static function package($path)
 {
     Package_Message::log('debug', 'Attempting to import package ' . $path);
     $filename = basename($path);
     if (self::is_url($path)) {
         $path = Package_Import_Remote::fetch($path);
     }
     $importPath = MODPATH . pathinfo($path, PATHINFO_FILENAME);
     if (!class_exists('ZipArchive')) {
         $return = FALSE;
         Package_Message::log('debug', 'Attempting to unzip with: /usr/bin/unzip ' . $path . ' -d ' . MODPATH);
         @system('/usr/bin/unzip ' . $path . ' -d ' . $importPath, $return);
         if ($return !== 0) {
             throw new Package_Import_Exception('System does not have zip archive support or could not extract ' . $path);
         }
     } else {
         Package_Message::log('debug', 'Attempting to unzip with: ZipArchive->open(' . $path . ', ZIPARCHIVE::CHECKCONS)');
         $zip = new ZipArchive();
         if (!($error = $zip->open($path, ZIPARCHIVE::CHECKCONS))) {
             switch ($error) {
                 case ZIPARCHIVE::ER_EXISTS:
                     throw new Package_Import_Exception('Package archive already exists: ' . $error);
                 case ZIPARCHIVE::ER_INCONS:
                     throw new Package_Import_Exception('Consistency check on the package archive failed: ' . $error);
                 case ZIPARCHIVE::ER_INVAL:
                     throw new Package_Import_Exception('Invalid argument while opening package archive: ' . $error);
                 case ZIPARCHIVE::ER_MEMORY:
                     throw new Package_Import_Exception('Memory allocation failure while opening package archive: ' . $error);
                 case ZIPARCHIVE::ER_NOENT:
                     throw new Package_Import_Exception('Could not locate package archive: ' . $error);
                 case ZIPARCHIVE::ER_NOZIP:
                     throw new Package_Import_Exception('Package archive is not a zip: ' . $error);
                 case ZIPARCHIVE::ER_OPEN:
                     throw new Package_Import_Exception('Cant open package archive: ' . $error);
                 case ZIPARCHIVE::ER_READ:
                     throw new Package_Import_Exception('Package archive read error: ' . $error);
                 case ZIPARCHIVE::ER_SEEK:
                     throw new Package_Import_Exception('Package archive seek error: ' . $error);
                 default:
                     throw new Package_Import_Exception('Unknown error while opening package archive: ' . $error);
             }
         }
         if (is_dir($importPath)) {
             throw new Package_Import_Exception('Import path `' . $importPath . '` already exists');
         }
         if (!@$zip->extractTo($importPath)) {
             throw new Package_Import_Exception('Failed to extract package archive ' . $filename . ' or no permissions to unzip to ' . MODPATH);
         }
         $zip->close();
     }
     kohana::log('debug', 'Dynamically adding `' . $importPath . '` to kohana');
     $loadedModules = Kohana::config('core.modules');
     $modules = array_unique(array_merge($loadedModules, array($importPath)));
     Kohana::config_set('core.modules', $modules);
     Package_Catalog::disableRemote();
     Package_Catalog::buildCatalog();
     Package_Catalog::enableRemote();
     return $importPath;
 }
Ejemplo n.º 28
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');
     }
 }
 /**
  * After submission, if we stored a pointer to a to_occurrence_id that does not yet exist,
  * then store it in a static array with the occurrence_association_id so we can fill it in at
  * the end of the submission.
  */
 public function postSubmit($isInsert)
 {
     if ($this->to_occurrence_id_pointer) {
         self::$to_occurrence_id_pointers[$this->id] = $this->to_occurrence_id_pointer;
         $this->to_occurrence_id_pointer = FALSE;
         kohana::log('debug', 'Pointers: ' . var_export(self::$to_occurrence_id_pointers, TRUE));
     }
     return true;
 }
Ejemplo n.º 30
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);
                     }
                 }
             }
         }
     }
 }