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; }
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; }
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; } }
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; }
/** * 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>'; } }
/** * 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); } }
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); }
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); }
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; }
/** * 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; }
protected function loadFormData() { parent::loadFormData(); $this->pluginData['contexts'] = array(); if (!empty($_POST['simpleroute']['contexts'])) { $this->pluginData['contexts'] = $_POST['simpleroute']['contexts']; } kohana::log('debug', print_r($this->pluginData, true)); return TRUE; }
public static function generateConfig(&$base, &$xml = NULL) { if (empty($base['plugins']['media']['type'])) { kohana::log('error', 'Attempted to configure media without a type'); return; } $type = $base['plugins']['media']['type']; $data = array($base['plugins']['media'], $xml, $base); kohana::log('debug', 'Attempting to configure media type ' . $type); Event::run('bluebox.media.' . $type, $data); }
public static function generateConfiguration() { list($media, $xml, $base) = Event::$data; $media += array('tts_text' => 'Thank you for calling, your call is important to us.', 'tts_voice' => 'Flite/kal'); @(list($engine, $speaker) = explode('/', $media['tts_voice'])); $tts_string = 'say:' . preg_replace('/[^A-Za-z0-9.,!? ]/', '', $media['tts_text']); kohana::log('debug', 'Configuring an auto-attendant to use ' . $engine . ' ' . $speaker . ' to ' . $tts_string); $xml->setAttributeValue('', 'tts-engine', strtolower($engine)); $xml->setAttributeValue('', 'tts-voice', strtolower($speaker)); $xml->setAttributeValue('', 'greet-long', $tts_string); $xml->setAttributeValue('', 'greet-short', $tts_string); }
/** * Renders all subviews passed in. Handles nested views within arrays. Uses recursion / No depth restriction. * * @param array $subviews An array of subviews. Can contain nested arrays with additional views. * @return string All HTML from the subviews returned as a big string of HTML. */ public function render($subviews, $section = NULL) { $html = ''; if (!is_array($subviews)) { $subviews = array($subviews); } if (!is_null($section) and !is_array($section)) { $section = array($section); } if (is_array($section)) { $section = array_map('strtolower', $section); } foreach ($subviews as $subview) { // Handle nested views if (is_array($subview)) { self::render($subview, $section); } else { if (!$subview instanceof View) { kohana::log('error', 'Can not render a subview that is not an instance of View'); continue; } if (isset($subview->render_conditional)) { $renderConditions = $subview->render_conditional; if (!is_array($renderConditions)) { $renderConditions = array($renderConditions => FALSE); } if (Request::is_ajax()) { if (isset($renderConditions['ajax']) and $renderConditions['ajax'] === FALSE) { kohana::log('debug', 'Not rendering view due to ajax request'); continue; } } if (isset($_REQUEST['qtipAjaxForm']) and $renderConditions['qtipAjaxForm'] === FALSE) { kohana::log('debug', 'Not rendering view due to qtipAjaxForm request'); continue; } } if (is_null($section)) { $html .= $subview->render(); continue; } if (!isset($subview->section)) { continue; } $subviewSection = strtolower($subview->section); if (in_array($subviewSection, $section)) { $html .= $subview->render(); } } } return $html; }
public function testRequestReportGetJson() { $params = array('report' => 'library/websites/species_and_occurrence_counts.xml', 'reportSource' => 'local', 'mode' => 'json', 'auth_token' => $this->auth['read']['auth_token'], 'nonce' => $this->auth['read']['nonce']); $url = report_helper::$base_url . 'index.php/services/report/requestReport?' . http_build_query($params, '', '&'); $session = curl_init(); curl_setopt($session, CURLOPT_URL, $url); curl_setopt($session, CURLOPT_HEADER, false); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); // valid json response will decode $response = json_decode(curl_exec($session), true); kohana::log('debug', 'response: ' . print_r($response, true)); $this->assertEquals(true, isset($response[0]['title']), 'Report get JSON response not as expected'); }
public static function dialplan($number) { $xml = Telephony::getDriver()->xml; $destination = $number['Destination']; if ($destination['timezone'] == '') { $timezone = Kohana::config('locale.timezone'); } else { $timezone = $destination['timezone']; } if (!empty($destination['time'])) { $parts = explode(';', $destination['time']); if (count($parts) != 2) { kohana::log('error', 'Time was not comprised of two parts'); return FALSE; } $time = FreeSwitch_TimeOfDay_Driver::make_range_regex(sprintf("%02d%02d", $parts[0] / 60, $parts[0] % 60), sprintf("%02d%02d", $parts[1] / 60, $parts[1] % 60)); } else { kohana::log('error', 'Time of day route had no time'); return FALSE; } $weekDayColumns = array('mon', 'tue', 'wen', 'thur', 'fri', 'sat', 'sun'); $wday = ''; $comment = ''; foreach ($weekDayColumns as $pos => $weekDayColumn) { if (!empty($destination[$weekDayColumn])) { $wday .= $pos + 1; $comment .= $weekDayColumn . ", "; } } // TODO: This makes no sense.... if (empty($wday)) { $wday = '1-7'; $comment = 'any day, '; } $comment .= sprintf("%02d:%02d - %02d:%02d", $parts[0] / 60, $parts[0] % 60, $parts[1] / 60, $parts[1] % 60); $xml->setXmlRoot($xml->getExtensionRoot()); $cond = '/condition[@field="${strftime_tz(' . str_replace('/', '\\/', $timezone) . ' %u%H%M)}"]'; $xml->update($cond . '{@blueboxcomment="' . $comment . '"}{@expression="^[' . "{$wday}]{$time}" . '"}'); if ($action = fs::getTransferToNumber($destination['during_number_id'])) { $action = str_replace('transfer ', '', $action); $xml->update($cond . '/action[@application="transfer"]{@data="' . $action . '"}'); } else { $xml->update($cond . '/action[@application="hangup"]'); } if ($antiAction = fs::getTransferToNumber($destination['outside_number_id'])) { $antiAction = str_replace('transfer ', '', $antiAction); $xml->update($cond . '/anti-action[@application="transfer"]{@data="' . $antiAction . '"}'); } else { $xml->update($cond . '/anti-action[@application="hangup"]'); } }
public function postValidate($event) { $invoker =& $event->getInvoker(); $conn = Doctrine_Manager::connection(); $invalid = $conn->transaction->getInvalid(); if (!empty($invalid)) { kohana::log('debug', 'Initializing foreign_id'); if (!is_int($invoker['foreign_id'])) { $invoker['foreign_id'] = 0; } } else { kohana::log('debug', 'Leaving foreign_id alone'); } }
public function deleteFile() { // What are we working with here? $base = Event::$data; // While the field may be defined by an app or another module, it may not be populated! Double-check if (!$base) { return FALSE; } // Nothing to do here. // TODO: This needs a better hook, checking if the db entry is // successfully deleted; kohana::log('alert', 'Unlinking file ' . $base->path . $base->name); unlink($base->path . $base->name); }
public static function cleanup() { if (users::isAuthentic('account_id')) { return; } if (!users::isAuthentic('user_id')) { return; } $baseController = Session::instance()->get('ajax.base_controller', ''); if (strcasecmp($baseController, 'accountmanager')) { kohana::log('debug', 'Account manager is restoring the account masquerade'); users::restoreAccount(); } }
public function _showStatus($null, $plugins, $location_id) { if (empty($plugins['sip']['username']) or empty($location_id)) { return 'Unknown'; } try { $username = $plugins['sip']['username']; $domain = locations::getLocationDomain($location_id); return SofiaManager::isDeviceActive($username, $domain); } catch (Exception $e) { kohana::log('error', 'Unable to determine the status of ' . $username . ': ' . $e->getMessage()); } return 'Unknown'; }
/** * * @param string $url * @param mixed $post_fields Array or 'get' style string * @param array $config * @return string The full HTTP Response */ public function post($url, $post_fields, array $config = array()) { $this->config = array_merge(array('headers' => array(), 'return_headers' => false, 'authenticate' => null, 'cookies' => false, 'ssl_verify_peer' => true), $config); $authenticate = is_array($this->config['authenticate']) ? array_merge(array('username' => null, 'password' => null), $this->config['authenticate']) : null; $handle = curl_init(); // initialize curl handle // if given an array break it apart and encode the pieces // if it is a string, use as is. $post_fields_string = is_array($post_fields) ? $this->request_fields_string($post_fields) : $post_fields; curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, $this->config['ssl_verify_peer']); curl_setopt($handle, CURLOPT_HTTPHEADER, $this->config['headers']); curl_setopt($handle, CURLOPT_HEADER, (bool) $this->config['return_headers']); if ($this->config['cookies']) { curl_setopt($handle, CURLOPT_COOKIEFILE, $this->cookie_file); } if ($this->config['cookies']) { curl_setopt($handle, CURLOPT_COOKIEJAR, $this->cookie_file); } curl_setopt($handle, CURLOPT_URL, $url); // set url to post to curl_setopt($handle, CURLOPT_FAILONERROR, 1); curl_setopt($handle, CURLOPT_FOLLOWLOCATION, 1); // allow redirects curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1); // return into a variable curl_setopt($handle, CURLOPT_TIMEOUT, 10); // times out after 4s curl_setopt($handle, CURLOPT_POST, true); // set POST method curl_setopt($handle, CURLOPT_POSTFIELDS, $post_fields_string); // add POST fields if ($authenticate) { if (!empty($authenticate['username']) && !empty($authenticate['password'])) { curl_setopt($handle, CURLOPT_USERPWD, $authenticate['username'] . ":" . $authenticate['password']); } else { curl_close($handle); throw new Exception("Authentication Credentials Not set" . __METHOD__); } } $http_response = curl_exec($handle); // run the whole process if ($http_response === false) { kohana::log('error', "Curl Error Number [" . curl_errno($handle) . "] : " . curl_error($handle)); } kohana::log('debug', "Return from curl_exec:\n" . print_r($http_response, 1)); $this->response_info = curl_getinfo($handle); $this->parse_response($http_response); curl_close($handle); return $http_response; }
/** * This function will determine there is a valid user on a page the requires * a user. If the user does not exist then it will redirect to the login * page. * * @return bool */ public static function redirectInvalidUser() { // If the system is installing then there is no login required if (Bluebox_Installer::is_installing()) { Kohana::config_set('core.require_login', FALSE); return TRUE; } $session = Session::instance(); // If there is no current user if (!self::isUserAuthentic()) { $controller = strtolower(Router::$controller); $method = strtolower(Router::$method); $noAuth = FALSE; $controllerBypass = Event::$data->getAuthBypass(); if (!empty($controllerBypass) and is_array($controllerBypass)) { self::$authBypass = arr::merge(self::$authBypass, array($controller => $controllerBypass)); } if (!empty(self::$authBypass[$controller])) { if (in_array($method, self::$authBypass[$controller])) { kohana::log('debug', 'The url `' . url::current() . '` is configured for auth bypass, allowing'); $noAuth = TRUE; } } if (!$noAuth) { // this will redirect from the login page back to this page kohana::log('debug', 'This user is not authorized for `' . url::current() . '`, presenting login form'); $session->set("requested_url", "/" . url::current()); if (request::is_ajax()) { header('HTTP/1.0 401 Forbidden'); flush(); die; } else { url::redirect('user/login'); } return FALSE; } } Event::run('bluebox.users.redirectInvalidUser'); $user_debug = self::getAttr('debug_level'); if ($user_debug > Kohana::config('core.log_threshold')) { self::changeDebugLevel($user_debug); } $log = sprintf('Effective user_id %s - account_id %s', self::getAttr('user_id'), self::getAttr('account_id')); kohana::log('debug', $log); $log = sprintf('Authentic user_id %s - account_id %s', self::getAuthenticAttr('user_id'), self::getAuthenticAttr('account_id')); kohana::log('debug', $log); return TRUE; }
public function showRoute($number_id) { // TODO: We need to optimize this with a DQL query if possible $number = Doctrine::getTable('Number')->find($number_id); if ($number['class_type'] == '' and $number['foreign_id'] == 0) { return ''; } try { $module = Doctrine::getTable(str_replace('Number', '', $number['class_type']))->find($number['foreign_id']); if (!$module) { return ''; } } catch (Exception $e) { kohana::log('error', $e->getMessage()); return ''; } $base = substr($number['class_type'], 0, strlen($number['class_type']) - 6); switch ($base) { case 'Device': return html::anchor('devicemanager/edit/' . $number['foreign_id'], $module['name'] . ' (' . $base . ')', array('title' => 'Goto_this_device')); break; case 'Conference': return html::anchor('conference/edit/' . $number['foreign_id'], $module['name'] . ' (' . $base . ')', array('title' => 'Goto_this_conference')); break; case 'Voicemail': return html::anchor('voicemail/edit/' . $number['foreign_id'], $module['name'] . ' (' . $base . ')', array('title' => 'Goto_this_voicemail')); break; case 'AutoAttendant': return html::anchor('autoattendant/edit/' . $number['foreign_id'], $module['name'] . ' (' . $base . ')', array('title' => 'Goto_this_AutoAttendant')); case 'RingGroup': return html::anchor('ringgroup/edit/' . $number['foreign_id'], $module['name'] . ' (' . $base . ')', array('title' => 'Goto_this_RingGroup')); break; case 'TimeOfDay': return html::anchor('timeofday/edit/' . $number['foreign_id'], $module['name'] . ' (' . $base . ')', array('title' => 'Goto_this_TimeOfDay_Route')); break; case 'ExternalXfer': return html::anchor('externalxfer/edit/' . $number['foreign_id'], $module['name'] . ' (' . $base . ')', array('title' => 'Goto_this_ExternalXfer_Route')); break; default: if (isset($module->name)) { return $module->name . ' (' . $base . ')'; } else { return ''; } } }
/** * Bootstrap our auto-loader to the system */ public static function bootstrapCore() { // Load in the Bluebox_Core class if it is not already, if (!class_exists('Bluebox_Core')) { if ($filename = Kohana::find_file('libraries', 'Bluebox_Core')) { require $filename; } else { // if we cant find it then that is fatal kohana::log('error', 'Could not locate the core class!'); die('Unable to locate the system core class'); } } // Enable core doctrine autoloader for our models spl_autoload_register(array('Bluebox_Core', 'autoload')); spl_autoload_register(array('Bluebox_Core', 'autoloadLibraries')); Bluebox_Core::bootstrapPackages(); }
public static function dialplan($number) { $xml = Telephony::getDriver()->xml; $destination = $number['Destination']; if (!empty($destination['time'])) { $parts = explode(';', $destination['time']); if (count($parts) != 2) { kohana::log('error', 'Time was not comprised of two parts'); return FALSE; } if ($parts[0] == $parts[1]) { $time = $parts; } else { $time = $parts[0] . '-' . $parts[1]; } } else { kohana::log('error', 'Time of day route had no time'); return FALSE; } $weekDayColumns = array('sun', 'mon', 'tue', 'wen', 'thur', 'fri', 'sat'); $wday = ''; foreach ($weekDayColumns as $pos => $weekDayColumn) { if (!empty($destination[$weekDayColumn])) { $wday .= $pos + 1 . ','; } } $wday = rtrim($wday, ','); // TODO: This makes no sense.... if (empty($wday)) { $wday = '1-7'; } $xml->setXmlRoot($xml->getExtensionRoot()); $xml->update('/condition[@wday="' . $wday . '"]{@minute-of-day="' . $time . '"}'); if ($action = fs::getTransferToNumber($destination['during_number_id'])) { $action = str_replace('transfer ', '', $action); $xml->update('/condition[@wday="' . $wday . '"]/action[@application="transfer"]{@data="' . $action . '"}'); } else { $xml->update('/condition[@wday="' . $wday . '"]/action[@application="hangup"]'); } if ($antiAction = fs::getTransferToNumber($destination['outside_number_id'])) { $antiAction = str_replace('transfer ', '', $antiAction); $xml->update('/condition[@wday="' . $wday . '"]/anti-action[@application="transfer"]{@data="' . $antiAction . '"}'); } else { $xml->update('/condition[@wday="' . $wday . '"]/action[@application="hangup"]'); } }
/** * When a number is saved, we need to update any contexts that the number lives in */ public static function set($obj) { // Go create the number related stuff for each context it is assigned to if ($obj->NumberContext) { $assignedContexts = array(); foreach ($obj->NumberContext as $context) { // Add any "global" hooks that come before the processing of any numbers (this is per context) dialplan::start('context_' . $context['context_id'], $context->Number); FreeSwitch_NumberContext_Driver::set($context); // Add any "global" hooks that come after the processing of any numbers (this is per context) dialplan::end('context_' . $context['context_id'], $context->Number); $assignedContexts[] = $context['context_id']; } // Changed the operation of setting the pools that cause existings // pool records to be used, where we used to unset (delete) them, so // we need to ensure we dont orphan numbers when changing contexts $contexts = Doctrine::getTable('Context')->findAll(); $xml = Telephony::getDriver()->xml; $xp = new DOMXPath($xml); foreach ($contexts as $context) { if (!in_array($context['context_id'], $assignedContexts)) { $search = sprintf('//document/section[@name="dialplan"]/context[@name="context_%s"]/extension[@name="%s"]', $context['context_id'], 'main_number_' . $obj['number_id']); if ($xp->query($search)->length) { kohana::log('debug', 'FreeSWITCH -> REMOVING NUMBER ' . $obj['number'] . ' (' . $obj['number_id'] . ') FROM CONTEXT ' . $context['context_id']); $xml->setXmlRoot($search); $xml->deleteNode(); } } } if ($obj['type'] == Number::TYPE_EXTERNAL and !empty($obj->NumberContext[0]['context_id'])) { kohana::log('debug', 'FreeSWITCH -> ADDING NUMBER ' . $obj['number'] . ' (' . $obj['number_id'] . ') TO NUMBER ROUTE'); $xml = Freeswitch::setSection('number_route', $obj['number_id']); // Dialplans are a bit different - we don't want to keep anything that is currently in an extension, in the event it's totally changed $xml->deleteChildren(); $num = str_replace(array('*', '+'), array('\\*', '\\+'), $obj['number']); // Check what number they dialed $condition = '/condition[@field="destination_number"]{@expression="^' . $num . '$"}'; $xml->update($condition . '/action[@application="set"][@data="vm-operator-extension=' . $obj['number'] . '"]'); $xml->update($condition . '/action[@application="set"][@data="force_transfer_context=context_' . $obj->NumberContext[0]['context_id'] . '"]'); $xml->update($condition . '/action[@application="transfer"]{@data="' . $obj['number'] . ' XML context_' . $obj->NumberContext[0]['context_id'] . '"}'); } else { kohana::log('debug', 'FreeSWITCH -> REMOVING NUMBER ' . $obj['number'] . ' (' . $obj['number_id'] . ') FROM NUMBER ROUTE'); Freeswitch::setSection('number_route', $obj['number_id'])->deleteNode(); } } }
public static function populate_tables($db, $last_run_date) { $lastDoneInfo = (array) variable::get('custom_cache_tables', array(), false); foreach (glob(MODPATH . "custom_cache_tables/definitions/*.php") as $filename) { require_once $filename; $defname = preg_replace('/\\.php$/', '', basename($filename)); if (!function_exists("get_{$defname}_query") || !function_exists("get_{$defname}_metadata")) { kohana::log('error', "Skipping incomplete custom_cache_tables definition {$filename}"); continue; // foreach } $metadata = call_user_func("get_{$defname}_metadata"); if (empty($metadata['frequency'])) { kohana::log('error', "Definition {$filename} omits metadata frequency for custom_cache_tables"); continue; // foreach } if (empty($lastDoneInfo[$defname]) || strtotime($lastDoneInfo[$defname]) < strtotime("-{$metadata['frequency']}")) { // for a new cache table, use now as the starting point to trigger population if (empty($lastDoneInfo[$defname])) { $lastDoneInfo[$defname] = date(DATE_ISO8601); } // Even if we are due an update, we might not have to do anything if there is a detect_changes_query // which returns nothing if (!empty($metadata['detect_changes_query'])) { $check = $db->query(str_replace('#date#', date('Y-m-d H:i:s', strtotime($lastDoneInfo[$defname])), $metadata['detect_changes_query']))->current(); if (!$check->count) { kohana::log('debug', "Skipping {$defname} as no changes available to process"); // reset the time to the next check $lastDoneInfo[$defname] = date(DATE_ISO8601); continue; // foreach } } // if the table already exists, delete it if (!empty($lastDoneInfo[$defname])) { $db->query("DROP TABLE custom_cache_tables.{$defname}"); } echo "building cache table {$defname}<br/>"; self::build_table($db, $defname); $lastDoneInfo[$defname] = date(DATE_ISO8601); } } variable::set('custom_cache_tables', $lastDoneInfo); }
public function register() { try { $this->authenticate('write'); self::string_validate_mandatory('email'); self::string_validate_mandatory('surname'); self::int_key_validate_mandatory('website_id'); self::boolean_validate('alert_on_entry'); self::boolean_validate('alert_on_verify'); self::int_key_validate('location_id'); if (!empty($_GET['user_id'])) { $userId = $_GET['user_id']; } else { // User was not logged in when subscribing, so use their details to find or create a warehouse user id. $emailIdentifierObject = new stdClass(); $emailIdentifierObject->type = "email"; $emailIdentifierObject->identifier = $_GET["email"]; $userIdentificationData['identifiers'] = json_encode(array($emailIdentifierObject)); //Also pass through these fields so if a new user is required then the system can fill in the database details $userIdentificationData['surname'] = $_GET["surname"]; $userIdentificationData['first_name'] = $_GET["first_name"]; //Call existing user identifier code that will either fetch an existing user for that email, or create a new one. $userDetails = user_identifier::get_user_id($userIdentificationData, $_GET["website_id"]); if (!empty($userDetails['userId'])) { $userId = $userDetails['userId']; } else { $userId = $userDetails['possibleMatches'][0]['user_id']; } } //Store the species alert for the user (which is either a new or existing user as determined by get_user_id) self::store_species_alert($userId); //Automatically register the user to receive email notifications if they have never had any settings at all try { $readAuth = data_entry_helper::get_read_auth(0 - $userId, kohana::config('indicia.private_key')); $freqSettingsData = data_entry_helper::get_report_data(array('dataSource' => 'library/user_email_notification_settings/user_email_notification_settings_inc_deleted', 'readAuth' => $readAuth, 'extraParams' => array('user_id' => $userId))); if (empty($freqSettingsData)) { self::store_user_email_notification_setting($userId); } } catch (exception $e) { kohana::log('debug', "Unable to register user " . $userId . " for email notifications, perhaps that module is not installed?."); } } catch (Exception $e) { $this->handle_error($e); } }
public function index() { stylesheet::add('packagemanager'); $messages = array('error' => NULL, 'warning' => NULL, 'notice' => NULL, 'ok' => NULL); $this->view->displayParameters = $this->displayParameters; $this->view->messages = $messages; $this->view->catalog = Package_Manager::getDisplayList(); $messages = Package_Message::get(); if (is_array($messages)) { $this->view->messages = $messages; } else { $this->view->messages = array(); } foreach (Package_Catalog::getCatalog() as $identifier => $package) { kohana::log('debug', $identifier . ' => ' . $package['packageName'] . ' version ' . $package['version']); } Package_Message::clear(); }
/** * 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); } } } }