Exemplo n.º 1
0
 /**
  * debug a message. Writes to stdout and to log file 
  * if debug = 1 is set in config
  * @param string $message 
  */
 public static function debug($message)
 {
     if (config::getMainIni('debug')) {
         log::error($message);
         return;
     }
 }
 public function postOrder()
 {
     log::debug('postOrder::Input params');
     log::debug(Input::all());
     //Validation rules
     $rules = array('pizza_marinara' => array('required', 'integer', 'between:0,3'), 'pizza_margherita' => array('required', 'integer', 'between:0,3'), 'olio' => array('min:1|max:20'), 'name' => array('required', 'min:1|max:20'), 'email' => array('required', 'email', 'min:1|max:20'), 'freeOrder' => array('exists:menu,dish'));
     // The validator
     $validation = Validator::make(Input::all(), $rules);
     // Check for fails
     if ($validation->fails()) {
         // Validation has failed.
         log::error('Validation has failed');
         $messages = $validation->messages();
         $returnedMsg = "";
         foreach ($messages->all() as $message) {
             $returnedMsg = $returnedMsg . " - " . $message;
         }
         log::error('Validation fail reason: ' . $returnedMsg);
         return redirect()->back()->withErrors($validation);
     }
     log::debug('Validation passed');
     $msg = array('email' => Input::get('email'), 'name' => Input::get('name'));
     $response = Event::fire(new ExampleEvent($msg));
     $response = Event::fire(new OrderCreated($msg));
     return view('orderdone', ['msg' => $msg]);
 }
Exemplo n.º 3
0
/**
 * @param \Exception $e
 * @return bool
 */
function exceptionHandler(\Exception $e)
{
    echo '<h1>Error</h1><p>Sorry, the script died with a exception</p>';
    echo $e->getMessage() . ' in <br>' . $e->getFile() . ': <br>' . $e->getLine(), ' : <br>', __FUNCTION__, ' : <br>', $e->getTraceAsString();
    log::error($e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine() . "<br>\n", "Code: " . $e->getCode(), $e->getTrace());
    mail(ADMIN_MAIL, '[GitReminder] System got locked', $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine() . "\n\n" . "Funktion -> " . __FUNCTION__ . $e->getTraceAsString() . "\n\n" . "Code: " . $e->getCode());
    @trigger_error('', E_USER_ERROR);
}
Exemplo n.º 4
0
 public static function vqueryf($conn, $sql, $args = array())
 {
     $sql = self::generate_sql($conn, $sql, $args);
     if (self::$log > 0) {
         self::$log--;
         log::debug($sql);
     }
     $result = mysql_query($sql, $conn);
     if ($error = mysql_error()) {
         log::error($error);
         return false;
     }
     return $result;
 }
Exemplo n.º 5
0
 /**
  * Gets the SSH session using the auth given
  *
  * @param \App\Models\Auth $auth Auth model
  * @param \Ssh\Configuration $configuration SSH configuration object
  */
 protected function getSSHSession($auth, $host)
 {
     $session = new SSH2($host);
     if ($auth->isKeyAuthentication()) {
         $key = new RSA();
         $key->loadKey($auth->credentials->key);
         if (!$session->login($auth->credentials->username, $key)) {
             \log::error('Login Failed');
         }
     } else {
         if (!$session->login($auth->credentials->username, $auth->credentials->password)) {
             \log::error('Login Failed');
         }
     }
     return $session;
 }
Exemplo n.º 6
0
/**
 * 自动加载类库处理
 * @return void
 */
function __autoload($classname)
{
    $classname = preg_replace("/[^0-9a-z_]/i", '', $classname);
    if (class_exists($classname)) {
        return true;
    }
    $classfile = $classname . '.php';
    try {
        if (file_exists(PATH_LIBRARY . '/' . $classfile)) {
            require PATH_LIBRARY . '/' . $classfile;
        } else {
            throw new Exception('Error: Cannot find the ' . $classname);
        }
    } catch (Exception $e) {
        log::error($e->getMessage() . '|' . $classname);
        exit;
    }
}
Exemplo n.º 7
0
 static function item_created($item)
 {
     access::add_item($item);
     if ($item->is_photo() || $item->is_movie()) {
         // Build our thumbnail/resizes.
         try {
             graphics::generate($item);
         } catch (Exception $e) {
             log::error("graphics", t("Couldn't create a thumbnail or resize for %item_title", array("item_title" => $item->title)), html::anchor($item->abs_url(), t("details")));
             Kohana_Log::add("error", $e->getMessage() . "\n" . $e->getTraceAsString());
         }
         // If the parent has no cover item, make this it.
         $parent = $item->parent();
         if (access::can("edit", $parent) && $parent->album_cover_item_id == null) {
             item::make_album_cover($item);
         }
     }
 }
Exemplo n.º 8
0
 protected function run_query($sql, array $params = null)
 {
     $stmt = false;
     try {
         $stmt = $this->db->prepare($sql);
     } catch (PDOException $e) {
         log::error('Error preparing query on database: ' . $this->connectDetails['db'] . ' ' . $e->getMessage());
     }
     if (!$stmt) {
         return false;
     }
     if (!call_user_func(array($stmt, 'execute'), $params)) {
         $this->last_error = $stmt->errorInfo();
         log::$errorDetails = $this->last_error();
         log::error('Query executiong failed: ' . $this->last_error[2]);
     }
     return $stmt;
 }
Exemplo n.º 9
0
 /**
  * Create new entity with parameters
  */
 public static function create(array $params = array())
 {
     $class = get_called_class();
     $model = \lib\conf\models::${$class::$database}[$class::$table];
     $params['date_added'] = $params['date_updated'] = 'UNIX_TIMESTAMP()';
     $keys = array_keys($params);
     // check primary key possibilities
     if ($model['primary_key']['auto_increment']) {
         // primary key cannot be set if it is auto_increment
         if (!empty($params[$model['primary_key']['field']])) {
             log::error('cannot create with auto_increment key filled in: table: ' . $class::$table . ' field: ' . $model['primary_key']['field']);
             return false;
         }
     } else {
         // primary key must be filled in if not auto_increment
         if (empty($params[$model['primary_key']['field']])) {
             log::error('primary key unspecified: table: ' . $class::$table . ' field: ' . $model['primary_key']['field']);
             return false;
         }
     }
     $placeholders = $values = array();
     foreach ($keys as $key) {
         // if primary is auto_increment, then skip it
         if ($model['primary_key']['auto_increment'] && $model['primary_key']['field'] == $key) {
             continue;
         }
         if (!isset($model['fields'][$key])) {
             continue;
         }
         $column_list[] = $key;
         $placeholders[] = $model['fields'][$key];
         $values[] = $params[$key];
     }
     $column_list = '(`' . implode('`, `', $column_list) . '`)';
     $placeholders = '(' . implode(', ', $placeholders) . ')';
     $conn = self::get_database();
     database::vqueryf($conn, "INSERT INTO `{$class::$table}` {$column_list} VALUES {$placeholders}", $values);
     if ($model['primary_key']['auto_increment']) {
         $primary_key = mysql_insert_id($conn);
     } else {
         $primary_key = $params[$model['primary_key']['field']];
     }
     return $primary_key;
 }
Exemplo n.º 10
0
 /**
  * Registers a new injector
  * 
  * @param callable $function The function to register as an injector.
  * 
  * @return void
  */
 public static function register(callable $function)
 {
     $target = null;
     $method = null;
     if (is_string($function)) {
         if (strpos($function, '::') === false) {
             $method = $function;
         } else {
             $parts = explode('::', $function);
             $target = $parts[0];
             $method = $parts[1];
         }
     } elseif (is_array($function)) {
         $target = $function[0];
         $method = $function[1];
     }
     $has = false;
     $put = null;
     if (is_null($target) && !is_null($method)) {
         $put = $method;
         $has = in_array($method, self::$injectors);
     } elseif (!is_null($target) && !is_null($method)) {
         if (is_string($target)) {
             $put = sprintf('%s::%s', $target, $method);
             $has = in_array($put, self::$injectors);
         } else {
             $put = $function;
             foreach (self::$injectors as $v) {
                 if (is_array($v) && $v[0] == $put[0] && $v[1] == $put[1]) {
                     $has = true;
                     break;
                 }
             }
         }
     }
     if ($has) {
         log::notice('Method has already been registered as an injector.');
     }
     if (is_null($put)) {
         log::error('Error validating callback function registered status.');
     }
     self::$injectors[] = $put;
 }
Exemplo n.º 11
0
 protected function init(array $details)
 {
     if (!isset($this->db)) {
         $required_fields = array('server', 'port', 'path');
         foreach ($required_fields as $v) {
             if (!array_key_exists($v, $details)) {
                 log::error('Unable to connect to Solr database - missing required fields.');
             }
         }
         try {
             $this->db = sprintf('http%s://%s:%s%s', isset($details['secure']) && $details['secure'] ? 's' : '', $details['server'], $details['port'], $details['path']);
             @$this->ping();
             $this->connectDetails = $details;
         } catch (Exception $e) {
             $this->db = null;
             log:
             error('Unable to connect to solr database on ' . $details['server']);
         }
     }
 }
Exemplo n.º 12
0
Arquivo: get.php Projeto: Borvik/Munla
 /**
  * Returns a string for a class static callable method, with the class modified.
  * 
  * @param callable $callback    The callback method to modify and return.
  * @param string $appendToClass The string to append to the class for the new class name.
  * 
  * @return callable A callable string in the format class::function.
  */
 private static function static_callable($callback, $appendToClass = '')
 {
     if (is_string($callback)) {
         $parts = explode('::', $callback);
         return sprintf('%s%s::%s', $parts[0], $appendToClass, $parts[1]);
     } elseif (is_array($callback)) {
         return sprintf('%s%s::%s', $callback[0], $appendToClass, $callback[1]);
     }
     log::error('Invalid callback specified, unable to return static method string.');
 }
Exemplo n.º 13
0
Arquivo: db.php Projeto: Borvik/Munla
 /**
  * Performs a given query.
  * 
  * Used by other query methods, and also usefully for non-select queries.
  * 
  * @param string $sql The query to run.
  * @param mixed $params Could be an array of scalar values for a parameterized query, or for some database types an array of additional options.  May also be scalar values for a parameterized query.
  * 
  * @return mixed The query result.  Type differs based on database type.
  */
 public function raw_query($sql, $params = array())
 {
     if (!isset($this->db)) {
         if (error_reporting() !== 0) {
             log::error('Error running database query. Database connection not initialized.');
         }
         return false;
     }
     $args = func_get_args();
     if (count($args) > 1 && !is_array($params)) {
         array_shift($args);
         $params = $args;
     }
     return $this->run_query($sql, $params);
 }
Exemplo n.º 14
0
function log_error($str)
{
    log::error($str);
}
Exemplo n.º 15
0
 public function sp($sql, array &$params, $options = array())
 {
     if (!isset($this->db)) {
         if (error_reporting() !== 0) {
             log::error('Error running database query. Database connection not initialized.');
         }
         return false;
     }
     if (isset($options) && !is_array($options)) {
         $options = array();
     }
     $result = sqlsrv_query($this->db, $sql, $params, $options);
     if ($result === false && error_reporting() !== 0) {
         log::$errorDetails = $this->last_error();
         log::error('Error running query on database: ' . $this->connectDetails['db']);
     }
     if ($result !== false) {
         sqlsrv_next_result($result);
     }
     return $result;
 }
Exemplo n.º 16
0
 /**
  * 采用正则分析提取字段
  * 
  * @param mixed $html
  * @param mixed $selector
  * @return void
  * @author seatle <*****@*****.**> 
  * @created time :2016-09-18 10:17
  */
 public function get_fields_regex($html, $selector, $fieldname)
 {
     if (@preg_match_all($selector, $html, $out) === false) {
         log::error("Field(\"{$fieldname}\") the selector in the regex(\"{$selector}\") syntax errors\n");
         exit;
     }
     $array = array();
     if (!is_null($out[1])) {
         foreach ($out[1] as $v) {
             $array[] = trim($v);
         }
     }
     return $array;
 }
Exemplo n.º 17
0
 /**
  * Magic method to allow interacting with the user model through the user class.
  * 
  * @param string $name The method name to call.
  * @param array $args The parameters for the method to call.
  * 
  * @return mixed
  */
 public function __call($name, $args)
 {
     if (!isset($this->userModel)) {
         $this->userModel = $this->getUserModel();
     }
     if (isset($this->userModel) && is_object($this->userModel)) {
         if (get_class($this->userModel) == 'secureClass') {
             $obj = $this->userModel->getObject();
             if (method_exists($obj, $name) && is_callable(array($obj, $name))) {
                 return call_user_func_array(array($obj, $name), $args);
             }
             log::error(sprintf('The method "%s" does not exist for %s', $name, get_class($obj)));
         } elseif (method_exists($this->userModel, $name) && is_callable(array($this->userModel, $name))) {
             return call_user_func_array(array($this->userModel, $name), $args);
         }
         log::error(sprintf('The method "%s" does not exist for %s', $name, get_class($this->userModel)));
     }
     throw new Exception(sprintf('The method "%s" does not exist for %s.', $name, get_class($this)));
 }
Exemplo n.º 18
0
 /**
  * Magic method to allow the secured object to be converted into a string.
  * 
  * @return string
  */
 public function __toString()
 {
     if (method_exists($this->internal, '__toString') && is_callable(array($this->internal, '__toString'))) {
         return $this->internal->__toString();
     }
     log::error(sprintf('Object of class %s could not be converted to a string', get_class($this->internal)));
 }
Exemplo n.º 19
0
 private function error($msg)
 {
     log::error('emboss', $msg);
     message::error($msg);
 }
Exemplo n.º 20
0
 /**
  * Decrypts cipher encrypted by crypt::encrypt() previously.
  *
  * Encrypted cipher is decryptable in current session, only.
  *
  * crypt::encrypt() and crypt::decrypt() transparently work on systems
  * missing mcrypt support by always passing provided cleartext.
  *
  * @throws \RuntimeException raised on missing mcrypt
  * @throws \InvalidArgumentException raised on decrypting failed
  * @param string $cipher encrypted message
  * @return string decrypted message
  */
 public function decrypt($cipher)
 {
     // test for tag on cipher and pass back provided cipher as is if tag is missing
     if (substr($cipher, 0, 8) !== 'TXF!CIPH') {
         log::warning('actually not decrypting since cipher is not properly encrypted');
         return $cipher;
     }
     if (!is_callable('mcrypt_module_open')) {
         throw new \RuntimeException('missing mcrypt');
     }
     // actually decrypt provided cipher
     mcrypt_generic_init($this->cryptModule, $this->preparedKey(), $this->preparedIV());
     $decrypted = mdecrypt_generic($this->cryptModule, substr($cipher, 8));
     mcrypt_generic_deinit($this->cryptModule);
     // check integrity of decrypted message
     $cleartext = substr($decrypted, 20);
     $hash = substr($decrypted, 0, 20);
     if (sha1($cleartext, true) !== $hash) {
         log::error('decryption failed');
         throw new \InvalidArgumentException('decryption failed');
     }
     return $cleartext;
 }
Exemplo n.º 21
0
/**
 * Print work result
 *
 * @param  (string) (data) Data for a printing
 * @param  (string) (type) Type of result ('json' or 'text')
 * @return (bool) true
 */
function echoResult($data, $type)
{
    log::debug('Returned data: ' . var_export($data, true));
    $type = empty($type) ? 'json' : (string) $type;
    switch ($type) {
        case 'json':
            if (function_exists('json_encode')) {
                // since 0.1.8
                echo json_encode($data);
            } else {
                if (class_exists('FastJSON')) {
                    log::debug('PHP function json_encode() is unavailable, used FastJSON class, $data=' . var_export($data, true));
                    echo FastJSON::encode($data);
                } else {
                    log::error('PHP function json_encode() is unavailable and FastJSON class not exists');
                    die('{"status":0,"msg":"PHP function json_encode() is unavailable and FastJSON class not exists"}');
                }
            }
            break;
        case 'text':
            var_dump($data);
            break;
    }
    if (defined('DEBUG_MODE') && DEBUG_MODE) {
        log::emptyLine();
    }
    return true;
}
Exemplo n.º 22
0
// simple api for getting ip.
$api_ip = config::getMainIni('api_ip');
if (!$api_ip) {
    $api_ip = 'http://www.os-cms.net/api/your_addr.php';
}
$my_ip = @file_get_contents($api_ip);
if ($my_ip === false) {
    log::error("Could not get your public IP. No check of current DNS settings");
    return;
}
if (!IP::isPublic($my_ip)) {
    log::error("IP {$my_ip} is not public");
}
$my_ip = trim($my_ip);
$my_hostnames = config::getMainIni('my_hostnames');
// if more hosts use a comma seperated list
$url = config::getMainIni('api_url');
$url .= "?hostname={$my_hostnames}&myip={$my_ip}";
$user_agent = "User-Agent: noiphp/0.0.1 dennis.iversen@gmail.com";
$curl = new mycurl($url);
$curl->useAuth(true);
//$curl->setCert(config::getMainIni('cert'));
$email = config::getMainIni('email');
$password = config::getMainIni('password');
$curl->setName($email);
$curl->setPass($password);
$curl->setUserAgent($user_agent);
$curl->createCurl();
$result = $curl->getWebPage();
log::error($result);
die;
Exemplo n.º 23
0
 /**
  * Shorten a Gallery URL
  * @param  int    $item_id
  * @param  string $format
  * @return mixed  string|false
  */
 static function shorten_url($item_id, $format = 'json')
 {
     $item = ORM::factory("item", $item_id);
     $short_url = '';
     $long_url = url::abs_site($item->relative_url_cache);
     $parameters = array("login" => module::get_var("bitly", "login"), 'apiKey' => module::get_var("bitly", "api_key"), 'longUrl' => $long_url, 'domain' => module::get_var("bitly", "domain"), 'format' => $format);
     $request = self::_build_http_request('shorten', $parameters);
     $response = self::_http_post($request, self::$api_host);
     $json_response = json_decode($response->body[0]);
     $status_txt = $json_response->status_txt;
     if ('OK' == $status_txt) {
         $short_url = $json_response->data->url;
         // Save the link hash to the database
         $link = ORM::factory("bitly_link");
         $link->item_id = $item_id;
         $link->hash = $json_response->data->hash;
         $link->global_hash = $json_response->data->global_hash;
         $link->save();
         return $json_response->data->url;
     } else {
         $status_code = $json_response->status_code;
         log::error("content", "Shortened URL", "Error: {$status_code} {$status_txt} <a href=\"{$long_url}\">item</a>");
         return false;
     }
 }
Exemplo n.º 24
0
 /**
  * Post a status update to Twitter
  * @param int      $item_id
  */
 public function tweet($item_id)
 {
     access::verify_csrf();
     $item = ORM::factory("item", $item_id);
     $form = twitter::get_tweet_form($item);
     if ($form->validate()) {
         $item_url = url::abs_site($item->relative_url_cache);
         $user = $this->_get_twitter_user(identity::active_user()->id);
         $consumer_key = module::get_var("twitter", "consumer_key");
         $consumer_secret = module::get_var("twitter", "consumer_secret");
         require_once MODPATH . "twitter/vendor/twitteroauth/twitteroauth.php";
         $connection = new TwitterOAuth($consumer_key, $consumer_secret, $user->oauth_token, $user->oauth_token_secret);
         $message = $form->twitter_message->tweet->value;
         $response = $connection->post('statuses/update', array('status' => $message));
         if (200 == $connection->http_code) {
             message::success(t("Tweet sent!"));
             json::reply(array("result" => "success", "location" => $item->url()));
         } else {
             message::error(t("Unable to send, your Tweet has been saved. Please try again later."));
             log::error("content", "Twitter", t("Unable to send tweet: %http_code", array("http_code" => $connection->http_code)));
             json::reply(array("result" => "success", "location" => $item->url()));
         }
         $tweet->item_id = $item_id;
         !empty($response->id) ? $tweet->twitter_id = $response->id : ($tweet->twitter_id = NULL);
         $tweet->tweet = $message;
         $tweet->id = $form->twitter_message->tweet_id->value;
         $this->_save_tweet($tweet);
     } else {
         json::reply(array("result" => "error", "html" => (string) $form));
     }
 }
Exemplo n.º 25
0
 /**
  * Gets the form to process, or given the form to process - processes it.
  * 
  * @param string|null $form
  *   The form identifier of the form to process.
  * 
  * @return string|bool|null 
  *   When $form is null, returns either null or a string form identifier.
  *   When a form identifier is passed, returns a boolean indicating the success or failure of the form processing.
  */
 public static function process($form = null)
 {
     if (isset(self::$processed)) {
         log::warning('Invalid call to formHelper::process() - the form has already been processed.');
         return false;
     }
     if (!isset($form)) {
         if (is::existset(munla::$session, 'forms')) {
             foreach (munla::$session['forms'] as $csrfName => $csrfForms) {
                 foreach ($csrfForms as $formid => $f) {
                     if (!is::existset($f, 'callback') || !is_callable($f['callback'])) {
                         continue;
                     }
                     $_FORM = array();
                     switch (strtolower($f['method'])) {
                         case 'post':
                             $_FORM =& $_POST;
                             break;
                         case 'get':
                             $_FORM =& $_GET;
                             break;
                     }
                     if (!is::existset($_FORM, 'mnl_formid')) {
                         unset($_FORM);
                         continue;
                     }
                     if (substr($_FORM['mnl_formid'], 0, strlen($csrfName) + 1) == $csrfName . '-' && substr($_FORM['mnl_formid'], strlen($csrfName) + 1) == $formid) {
                         unset($_FORM);
                         return sprintf('%s::%s', $csrfName, $formid);
                     }
                     unset($_FORM);
                 }
             }
         }
         $mnl_formaction = self::validateAction(is::existset($_POST, 'mnl_formaction') ? $_POST['mnl_formaction'] : (is::existset($_GET, 'mnl_formaction') ? $_GET['mnl_formaction'] : null));
         if ($mnl_formaction) {
             return 'simpleForm::' . $mnl_formaction;
         }
         return $form;
     }
     if (!is_string($form) || strpos($form, '::') === false) {
         log::error(sprintf('Invalid form identifier "%s"', $form));
         return false;
     }
     list($csrfName, $formid) = explode('::', $form, 2);
     if ($csrfName == 'simpleForm' && is_callable($formid)) {
         //$formid(); //trigger the callback - we don't know the values or form definition so no parameters
         $_FORM = array();
         if (is::existset($_POST, 'mnl_formaction')) {
             $_FORM =& $_POST;
         }
         if (is::existset($_GET, 'mnl_formaction')) {
             $_FORM =& $_GET;
         }
         self::fixArrays();
         unset($_FORM['mnl_formaction']);
         //normalize the file listing into a better array if any files were uploaded
         self::fixFileArray($_FORM);
         self::$processed = array('errors' => array(), 'fielderrors' => array(), 'msg' => null);
         self::$processed['form']['formid'] = $formid;
         $p = get::helper('form');
         $processed = call_user_func($formid, $p, $_FORM);
         if ($processed === false) {
             self::$processed['errors'][] = 'Failed to process the form.';
         } elseif ($processed !== true) {
             if (is_array($processed)) {
                 foreach ($processed as $err) {
                     $success = false;
                     switch (substr($err, 0, 1)) {
                         case '+':
                             $err = substr($err, 1);
                             $success = true;
                             break;
                         case '-':
                             $err = substr($err, 1);
                             break;
                     }
                     self::$processed[$success ? 'msg' : 'errors'][] = $err;
                 }
             } else {
                 $success = false;
                 switch (substr($processed, 0, 1)) {
                     case '+':
                         $processed = substr($processed, 1);
                         $success = true;
                         break;
                     case '-':
                         $processed = substr($processed, 1);
                         break;
                 }
                 self::$processed[$success ? 'msg' : 'errors'][] = $processed;
             }
         }
         return count(self::$processed['errors']) < 1;
     }
     if (!is::existset(munla::$session, 'forms') || !is::existset(munla::$session['forms'], $csrfName) || !is::existset(munla::$session['forms'][$csrfName], $formid)) {
         log::error(sprintf('Specified form definition "%s" was not found', $form));
         return false;
     }
     $form = munla::$session['forms'][$csrfName][$formid];
     if (!is::existset($form, 'callback') || !is_callable($form['callback'])) {
         log::error(sprintf('Form does not have a valid callback.'));
         return false;
     }
     $callback = explode('::', $form['callback']);
     $_FORM = array();
     switch (strtolower($form['method'])) {
         case 'post':
             $_FORM =& $_POST;
             break;
         case 'get':
             $_FORM =& $_GET;
             break;
     }
     self::fixArrays();
     self::$processed = array('errors' => array(), 'fielderrors' => array(), 'msg' => null);
     self::$processed['form'] = $form;
     if (is::existset($_FORM, 'mnl_formid')) {
         unset($_FORM['mnl_formid']);
     }
     //normalize the file listing into a better array if any files were uploaded
     self::fixFileArray($_FORM);
     //fix up special field types
     foreach ($form['fields'] as $field) {
         $type = get_class($field);
         if ($type == 'fe_image') {
             $name = $field->getName();
             if (!is::existset($_FORM, $name) && is::existset($_FORM, $name . '_x')) {
                 $_FORM[$name] = true;
             }
         } elseif ($type == 'fe_session') {
             $_FORM[$field->getName()] = $field->get_value();
         }
     }
     $fields = new formFieldList($form['fields']);
     $validating = array($callback[0], $callback[1] . '_validating');
     $validate = array($callback[0], $callback[1] . '_validate');
     if (is_callable($validating)) {
         $validating($this, $fields, $_FORM);
     }
     $valid = is_callable($validate) ? $validate($_FORM) : self::validate($fields, $_FORM, strtolower($form['method']) == 'post' && !$form['nocsrf']);
     if ($valid) {
         $processed = $callback($_FORM);
         if (isset($processed)) {
             if ($processed === false) {
                 self::$processed['errors'][] = 'Failed to process the form.';
             } elseif ($processed !== true) {
                 if (is_array($processed)) {
                     foreach ($processed as $err) {
                         $success = false;
                         switch (substr($err, 0, 1)) {
                             case '+':
                                 $err = substr($err, 1);
                                 $success = true;
                                 break;
                             case '-':
                                 $err = substr($err, 1);
                                 break;
                         }
                         self::$processed[$success ? 'msg' : 'errors'][] = $err;
                     }
                 } else {
                     $success = false;
                     switch (substr($processed, 0, 1)) {
                         case '+':
                             $processed = substr($processed, 1);
                             $success = true;
                             break;
                         case '-':
                             $processed = substr($processed, 1);
                             break;
                     }
                     self::$processed[$success ? 'msg' : 'errors'][] = $processed;
                 }
             }
         }
     } elseif (count(self::$processed['errors']) < 1) {
         self::$processed['errors'][] = 'Failed form validation.';
     }
     return count(self::$processed['errors']) < 1;
 }
Exemplo n.º 26
0
 /**
  * Post a status update to Twitter
  * @param int      $item_id
  */
 public function tweet($item_id)
 {
     access::verify_csrf();
     $item = ORM::factory("item", $item_id);
     $form = twitter::get_tweet_form($item);
     if ($form->validate()) {
         $item_url = url::abs_site($item->relative_url_cache);
         $user = $this->_get_twitter_user(identity::active_user()->id);
         $consumer_key = module::get_var("twitter", "consumer_key");
         $consumer_secret = module::get_var("twitter", "consumer_secret");
         require_once MODPATH . "twitter/vendor/twitteroauth/twitteroauth.php";
         $connection = new TwitterOAuth($consumer_key, $consumer_secret, $user->oauth_token, $user->oauth_token_secret);
         $message = $form->twitter_message->tweet->value;
         $attach_image = $form->twitter_message->attach_image->value;
         if ($attach_image == 1) {
             $filename = APPPATH . "../var/resizes/" . $item->relative_path_cache;
             $handle = fopen($filename, "rb");
             $image = fread($handle, filesize($filename));
             fclose($handle);
             $response = $connection->upload('statuses/update_with_media', array('media[]' => "{$image};type=image/jpeg;filename={$filename}", 'status' => $message));
         } else {
             $response = $connection->post('statuses/update', array('status' => $message));
         }
         if (200 == $connection->http_code) {
             message::success(t("Tweet sent!"));
             json::reply(array("result" => "success", "location" => $item->url()));
         } else {
             message::error(t("Unable to send, your Tweet has been saved. Please try again later: %http_code, %response_error", array("http_code" => $connection->http_code, "response_error" => $response->error)));
             log::error("content", "Twitter", t("Unable to send tweet: %http_code", array("http_code" => $connection->http_code)));
             json::reply(array("result" => "success", "location" => $item->url()));
         }
         $tweet->item_id = $item_id;
         !empty($response->id) ? $tweet->twitter_id = $response->id : ($tweet->twitter_id = NULL);
         $tweet->tweet = $message;
         $tweet->id = $form->twitter_message->tweet_id->value;
         $this->_save_tweet($tweet);
     } else {
         json::reply(array("result" => "error", "html" => (string) $form));
     }
 }
Exemplo n.º 27
0
function catch_fatal_error()
{
    $error = error_get_last();
    if (!empty($error)) {
        $tmp = var_export($error, true);
        log::error($tmp);
    }
}
Exemplo n.º 28
0
 /**
  * Run a task.  This will trigger the task to do a small amount of work, then it will report
  * back with status on the task.
  * @param string $task_id
  */
 public function run($task_id)
 {
     access::verify_csrf();
     try {
         $task = task::run($task_id);
     } catch (Exception $e) {
         Kohana::log("error", sprintf("%s in %s at line %s:\n%s", $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString()));
         throw $e;
     }
     if ($task->done) {
         switch ($task->state) {
             case "success":
                 log::success("tasks", t("Task %task_name completed (task id %task_id)", array("task_name" => $task->name, "task_id" => $task->id)), html::anchor("admin/maintenance", t("maintenance")));
                 message::success(t("Task completed successfully"));
                 break;
             case "error":
                 log::error("tasks", t("Task %task_name failed (task id %task_id)", array("task_name" => $task->name, "task_id" => $task->id)), html::anchor("admin/maintenance", t("maintenance")));
                 message::success(t("Task failed"));
                 break;
         }
         print json_encode(array("result" => "success", "task" => array("percent_complete" => $task->percent_complete, "status" => $task->status, "done" => $task->done), "location" => url::site("admin/maintenance")));
     } else {
         print json_encode(array("result" => "in_progress", "task" => array("percent_complete" => $task->percent_complete, "status" => $task->status, "done" => $task->done)));
     }
 }
Exemplo n.º 29
0
 /**
  * Run a task.  This will trigger the task to do a small amount of work, then it will report
  * back with status on the task.
  * @param string $task_id
  */
 public function run($task_id)
 {
     access::verify_csrf();
     $task = ORM::factory("task", $task_id);
     if (!$task->loaded) {
         throw new Exception("@todo MISSING_TASK");
     }
     $task->state = "running";
     call_user_func_array($task->callback, array(&$task));
     $task->save();
     if ($task->done) {
         switch ($task->state) {
             case "success":
                 log::success("tasks", t("Task %task_name completed (task id %task_id)", array("task_name" => $task->name, "task_id" => $task->id)), html::anchor(url::site("admin/maintenance"), t("maintenance")));
                 message::success(t("Task completed successfully"));
                 break;
             case "error":
                 log::error("tasks", t("Task %task_name failed (task id %task_id)", array("task_name" => $task->name, "task_id" => $task->id)), html::anchor(url::site("admin/maintenance"), t("maintenance")));
                 message::success(t("Task failed"));
                 break;
         }
         print json_encode(array("result" => "success", "task" => $task->as_array(), "location" => url::site("admin/maintenance")));
     } else {
         print json_encode(array("result" => "in_progress", "task" => $task->as_array()));
     }
 }