Example #1
0
File: go.php Project: Borvik/Munla
 /**
  * Attempts to redirect the user to the last page they
  * were on. If there is no history, then processing continues.
  * 
  * @return bool FALSE on failure.
  */
 public static function back()
 {
     if (is::existset(munla::$session, 'lastpage') && strlen(munla::$session['lastpage']) > 0) {
         return go::url(munla::$session['lastpage']);
     }
     return false;
 }
Example #2
0
 /**
  * Generates the HTML for the form element.
  * 
  * @return string
  */
 public function __toString()
 {
     $this->attributes['id'] = $this->getId();
     $this->attributes['name'] = $this->getName();
     $this->attributes['type'] = $this->type;
     $html = sprintf('<input%s />', get::formattedAttributes($this->getAttributes()));
     if (is::existset($this->attributes, 'autofocus')) {
         $html .= $this->getAutoFocusScript($this->attributes['id']);
     }
     return $html;
 }
Example #3
0
 /**
  * Generates the HTML for the form element.
  * 
  * @return string
  */
 public function __toString()
 {
     $this->attributes['id'] = $this->getId();
     $this->attributes['name'] = $this->getName();
     $value = get::array_def($this->attributes, 'value', '');
     $html = sprintf('<textarea%s>%s</textarea>', get::formattedAttributes($this->getAttributes()), get::entities($value));
     if (is::existset($this->attributes, 'autofocus')) {
         $html .= $this->getAutoFocusScript($this->attributes['id']);
     }
     return $html;
 }
Example #4
0
 /**
  * Generates the HTML for the form element.
  * 
  * @return string
  */
 public function __toString()
 {
     $this->attributes['id'] = $this->getId();
     $this->attributes['name'] = $this->getName();
     $this->attributes['value'] = get::array_def($this->attributes, 'value', '');
     $this->attributes['type'] = $this->type;
     $content = get::array_def($this->attributes, 'content', $this->attributes['value']);
     $html = sprintf('<button%s>%s</button>', get::formattedAttributes($this->getAttributes()), $content);
     if (is::existset($this->attributes, 'autofocus')) {
         $html .= $this->getAutoFocusScript($this->attributes['id']);
     }
     return $html;
 }
Example #5
0
File: get.php Project: Borvik/Munla
 /**
  * Gets a url.
  * 
  * A robust method of getting url, with many options depending on the paramters.
  * With no parameters, it gets the current url.
  * With a single string parameter
  *   starts with "www.": return scheme with the parameter
  *   already a url: returns the url
  *   a FILE path: url to file, or just the filename if the file is inaccessible to the DOCUMENT_ROOT
  *   the path after the domain: full url with the path replace with the given path
  *   equals 'http' or 'https': converts current url to http or https
  * 
  * Multiple parameters (see parameters for details).  Multiple parameters may also be passed
  * as an associative array.
  * 
  * Any parameter may be skipped, though they must be in order.
  * 
  * Some parameters require prior parameters to be passed (such as argSeparator) otherwise
  * it may be mistaken for an eariler parameter.
  * 
  * @param string $webpath      The path following the domain name.
  * @param string|bool $https   Whether the url should be secure or not. Valid values: true, false, 'http', 'https'.
  * @param int $port            The port number that should be used (ex. http://www.google.com:57/).
  * @param string|array $get    The query string that should be appended to the url.
  * @param string $argSeparator The separator that should splite arguements in the query string.
  * 
  * @return string Returns the url, or just the filename for inaccessible file paths.
  */
 public static function cache_url()
 {
     // get the arguements
     $args = func_get_args();
     $noArgs = count($args) == 0 || count($args) == 1 && is_bool($args[0]);
     $fallback = null;
     if (count($args) == 1 && is_string($args[0])) {
         if (strlen($args[0]) > 4 && strtolower(substr($args[0], 0, 4)) == 'www.') {
             return 'http' . (is::ssl() ? 's' : '') . '://' . $args[0];
         }
         $file_url = self::file_url($args[0]);
         if (is::url($file_url)) {
             return $file_url;
         }
         //if( file_exists($args[0]) || file_exists(MUNLA_APP_DIR.$args[0]) ) return self::file_url($args[0];//file url
         if (is::url($args[0])) {
             return $args[0];
         }
         $fallback = $args[0];
     }
     $webpath = null;
     $https = null;
     $port = null;
     $get = null;
     $argSeparator = '&';
     if (count($args) == 1 && is_array($args[0])) {
         $vargs = array('webpath', 'https', 'port', 'get', 'argSeparator');
         $is_assoc = false;
         //must use this method rather than is::assoc_array because GET can be an assoc array
         foreach ($vargs as $v) {
             if (is::existset($args[0], $v)) {
                 $is_assoc = true;
                 break;
             }
         }
         if ($is_assoc) {
             //arguements were passed as associative array
             if (is::existset($args[0], 'webpath')) {
                 $webpath = $args[0]['webpath'];
             }
             if (is::existset($args[0], 'https')) {
                 $https = $args[0]['https'] == 'https' || $args[0]['https'] === true;
             }
             if (is::existset($args[0], 'port')) {
                 $port = $args[0]['port'];
             }
             if (is::existset($args[0], 'get')) {
                 $get = $args[0]['get'];
             }
             if (is::existset($args[0], 'argSeparator')) {
                 $argSeparator = $args[0]['argSep'];
             }
         } else {
             $get = $args[0];
         }
         //not an associative array, the array is meant for get
     } else {
         // cycle through the arguments and assign them based on type
         // remember to not go out of order
         // webpath,  https,      port,     get,      argSeparator
         // string , bool|string,  int, string|array, string
         $argPos = 0;
         while (count($args) > 0) {
             $arg = array_shift($args);
             if (is_string($arg)) {
                 $argl = strtolower($arg);
                 if ($argPos <= 1 && ($argl == 'https' || $argl == 'http')) {
                     $argPos = 2;
                     $https = $argl == 'https';
                     continue;
                 }
                 if ($argPos > 0 && $argPos <= 3) {
                     if (strlen($arg) > 1) {
                         $get = $arg;
                     }
                     $argPos = 4;
                     continue;
                 }
                 if ($argPos > 3) {
                     $argSeparator = $arg;
                     break;
                 }
                 if ($argPos < 1) {
                     $webpath = $arg;
                     $argPos = 1;
                     continue;
                 }
             }
             if ($argPos <= 1 && is_bool($arg)) {
                 $https = $arg;
                 $argPos = 2;
             }
             if ($argPos <= 2 && is_int($arg)) {
                 $port = $arg;
                 $argPos = 3;
             }
             if ($argPos <= 3 && is_array($arg)) {
                 $get = $arg;
                 $argPos = 4;
             }
         }
     }
     //var_dump(array('webpath' => $webpath, 'https' => $https, 'port' => $port, 'get' => $get, 'argSeparator' => $argSeparator));
     if (!isset($https)) {
         $https = is::ssl();
     }
     if (isset($webpath) && is::url($webpath)) {
         if (strlen($webpath) > 4 && strtolower(substr($webpath, 0, 4)) == 'www.') {
             return 'http' . ($https ? 's' : '') . '://' . $webpath;
         }
         if (is::url($webpath)) {
             //convert http to https or https to http
             if (strtolower(substr($webpath, 0, 6)) == 'http:/' && $https) {
                 return 'https:/' . substr($webpath, 6);
             }
             if (strtolower(substr($webpath, 0, 6)) == 'https:' && !$https) {
                 return 'http:' . substr($webpath, 6);
             }
             return $webpath;
         }
     }
     //get the port number to use - only use if it doesn't match the default
     $portNum = isset($port) && ctype_digit((string) $port) ? ':' . $port : '';
     if ($portNum == '') {
         if ($https) {
             if (config::$https_port != 443) {
                 $portNum = ':' . config::$https_port;
             }
         } else {
             if (config::$http_port != 80) {
                 $portNum = ':' . config::$http_port;
             }
         }
     }
     // convert get into an array
     if ($noArgs && !isset($get)) {
         if (is::existset($_SERVER, 'QUERY_STRING')) {
             parse_str($_SERVER['QUERY_STRING'], $get);
         }
     } else {
         if (isset($get) && is_string($get)) {
             $gs = $get;
             $get = array();
             parse_str($gs, $get);
         }
     }
     if (!isset($get) || !is_array($get)) {
         $get = array();
     }
     // get the domain
     $domain = $_SERVER['SERVER_NAME'];
     if ($https && isset(config::$https_domain) && $https != is::ssl() && $_SERVER['SERVER_NAME'] != config::$https_domain) {
         //shared ssl domain, pass original domain to GET
         $domain = config::$https_domain;
         $get['r_domain'] = get::subdomain(null, 'www');
         //$_SERVER['SERVER_NAME'];
     } elseif (!$https && $https != is::ssl()) {
         //non-ssl find non-ssl domain (for shared SSL domains)
         $found = false;
         if (is::existset($_SERVER, 'QUERY_STRING')) {
             parse_str($_SERVER['QUERY_STRING'], $sqs);
             if (is::existset($sqs, 'r_domain')) {
                 $domain = get::fulldomain($sqs['r_domain']);
                 $found = true;
             }
         }
         //fallback to config if set
         if (!$found && isset(config::$http_domain)) {
             $domain = config::$http_domain;
         }
         if (isset($get['r_domain'])) {
             unset($get['r_domain']);
         }
     } elseif ($https && isset(config::$https_domain) && !isset($get['r_domain'])) {
         if (is::existset($_SERVER, 'QUERY_STRING')) {
             parse_str($_SERVER['QUERY_STRING'], $sqs);
             if (is::existset($sqs, 'r_domain')) {
                 $get['r_domain'] = $sqs['r_domain'];
             }
         }
     }
     // if webpath isn't set - use the current webpath
     if (!isset($webpath)) {
         $qs = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
         $webpath = substr($_SERVER['REQUEST_URI'], 0, strlen($_SERVER['REQUEST_URI']) - strlen($qs));
         if (substr($webpath, -1) == '?') {
             $webpath = substr($webpath, 0, -1);
         }
     }
     // if the webpath doesn't start with the web root, then prepend the web root
     if (strlen($webpath) > 0 && substr($webpath, 0, 1) != '/') {
         $webpath = '/' . $webpath;
     }
     //must run twice for proper root check
     if (substr($webpath, 0, strlen(MUNLA_WEB_ROOT)) != MUNLA_WEB_ROOT) {
         $webpath = MUNLA_WEB_ROOT . (substr($webpath, 0, 1) == '/' ? substr($webpath, 1) : $webpath);
     }
     $webpath = preg_replace('/^(\\/?index(\\.php)?)(\\/?index(\\.php)?)?/i', '', $webpath);
     if (strlen($webpath) > 0 && substr($webpath, 0, 1) != '/') {
         $webpath = '/' . $webpath;
     }
     // if a query string modifier is present - append it to the query string
     if (defined('QS_APPEND')) {
         if (!isset($get)) {
             $get = QS_APPEND;
         } elseif (is_array($get)) {
             if (is_array(QS_APPEND)) {
                 $get = $get + QS_APPEND;
             } else {
                 $prefix = array();
                 parse_str(QS_APPEND, $prefix);
                 $get = $get + $prefix;
             }
         } elseif (is_string($get)) {
             $pfx = strlen($get) > 0 ? $argSeparator : '';
             if (!is_array(QS_APPEND)) {
                 $get = $argSeparator . QS_APPEND;
             } else {
                 $get .= $argSeparator . http_build_query(QS_APPEND, '', $argSeparator);
             }
         }
     }
     //build the query string
     $qs = isset($get) && is_array($get) && count($get) ? '?' . http_build_query($get, '', $argSeparator) : (isset($get) && is_string($get) ? '?' . $get : '');
     //if built url is not valid - return fallback
     $webpath = implode('/', array_map('urlencode', explode('/', $webpath)));
     $url = sprintf('%s://%s%s%s%s', $https ? 'https' : 'http', $domain, $portNum, $webpath, $qs);
     if (!is::url($url)) {
         if (!isset($fallback)) {
             return sprintf('%s://%s%s', $https ? 'https' : 'http', $domain, $portNum);
         }
         return $fallback;
     }
     return $url;
 }
Example #6
0
 /**
  * Generates an anchor element.
  * 
  * @param mixed $name  The content of the anchor element.
  * @param string $webpath      The path following the domain name.
  * @param string|bool $https   Whether the url should be secure or not. Valid values: true, false, 'http', 'https'.
  * @param int $port            The port number that should be used (ex. http://www.google.com:57/).
  * @param string|array $get    The query string that should be appended to the url.
  * @param string $argSeparator The separator that should splite arguements in the query string.
  * @param array $attributes,... OPTIONAL Any number of associative arrays containing html attributes as the keys.
  * 
  * @return he_a
  */
 public function a($content, $webpath)
 {
     $args = func_get_args();
     array_shift($args);
     array_shift($args);
     $https = null;
     $port = null;
     $get = null;
     $argSeparator = '&';
     $attributes = array();
     $allowed = he_a::acceptedAttributes();
     if (count($args) == 1 && is_array($args[0])) {
         $vargs = array('https', 'port', 'get', 'argSeparator', 'attributes');
         $is_assoc = false;
         //must use this method rather than is::assoc_array because GET can be an assoc array
         foreach ($vargs as $v) {
             if (is::existset($args[0], $v)) {
                 $is_assoc = true;
                 break;
             }
         }
         if ($is_assoc) {
             //arguements were passed as associative array
             if (is::existset($args[0], 'https')) {
                 $https = $args[0]['https'] == 'https' || $args[0]['https'] === true;
             }
             if (is::existset($args[0], 'port')) {
                 $port = $args[0]['port'];
             }
             if (is::existset($args[0], 'get')) {
                 $get = $args[0]['get'];
             }
             if (is::existset($args[0], 'argSeparator')) {
                 $argSeparator = $args[0]['argSep'];
             }
             if (is::existset($args[0], 'attributes') && is_array($args[0]['attributes'])) {
                 $attributes = $args[0]['attributes'];
             }
         } else {
             if ($this->hasHtmlAttributes($args[0], $allowed)) {
                 $attributes = $args[0];
             } else {
                 $get = $args[0];
             }
             //not an associative array, the array is meant for get
         }
     } else {
         // cycle through the arguments and assign them based on type
         // remember to not go out of order
         //  https,      port,     get,      argSeparator, attributes
         // bool|string,  int, string|array, string,       array
         $argPos = 0;
         while (count($args) > 0) {
             $arg = array_shift($args);
             if (is_string($arg)) {
                 $argl = strtolower($arg);
                 if ($argPos < 1 && ($argl == 'https' || $argl == 'http')) {
                     $argPos = 1;
                     $https = $argl == 'https';
                     continue;
                 }
                 if ($argPos > 0 && $argPos <= 2) {
                     if (strlen($arg) > 1) {
                         $get = $arg;
                     }
                     $argPos = 3;
                     continue;
                 }
                 if ($argPos > 2) {
                     $argSeparator = $arg;
                     break;
                 }
             }
             if ($argPos < 1 && is_bool($arg)) {
                 $https = $arg;
                 $argPos = 1;
             }
             if ($argPos <= 1 && is_int($arg)) {
                 $port = $arg;
                 $argPos = 2;
             }
             if (is_array($arg)) {
                 if ($argPos <= 2) {
                     //must check for attributes
                     if ($this->hasHtmlAttributes($arg, $allowed)) {
                         foreach ($arg as $n => $v) {
                             $n = strtolower($n);
                             if (!array_key_exists($n, $attributes)) {
                                 if (array_key_exists($n, htmlElement::$enumAttributes) && !in_array($v, htmlElement::$enumAttributes[$n]) && array_key_exists($v, htmlElement::$enumAttributes[$n])) {
                                     $v = htmlElement::$enumAttributes[$n][$v];
                                 } elseif (in_array($n, htmlElement::$boolAttributes)) {
                                     if (is_bool($v) && !$v || !is_bool($v) && $v !== 'true') {
                                         continue;
                                     }
                                     $v = $n;
                                 }
                                 $attributes[$n] = $v;
                             }
                         }
                     } else {
                         $get = $arg;
                     }
                 }
                 if ($argPos > 2) {
                     //must be attributes
                     foreach ($arg as $n => $v) {
                         $n = strtolower($n);
                         if (!array_key_exists($n, $attributes)) {
                             if (array_key_exists($n, htmlElement::$enumAttributes) && !in_array($v, htmlElement::$enumAttributes[$n]) && array_key_exists($v, htmlElement::$enumAttributes[$n])) {
                                 $v = htmlElement::$enumAttributes[$n][$v];
                             } elseif (in_array($n, htmlElement::$boolAttributes)) {
                                 if (is_bool($v) && !$v || !is_bool($v) && $v !== 'true') {
                                     continue;
                                 }
                                 $v = $n;
                             }
                             $attributes[$n] = $v;
                         }
                     }
                     $argPos = 4;
                 }
             }
         }
     }
     $attributes['href'] = get::url($webpath, $https, $port, $get, $argSeparator);
     //, $attributes);
     $e = new he_a($content, $attributes);
     if (!$this->echoOff) {
         echo $e;
     }
     return $e;
 }
Example #7
0
 /**
  * Starts the application.
  * 
  * @return void
  */
 public static function run()
 {
     self::$starttime = microtime(true);
     error_reporting(config::ERROR_LEVEL);
     if (isset(config::$session_cookie_domain)) {
         ini_set('session.cookie_domain', config::$session_cookie_domain);
     }
     if (class_exists('formHelper')) {
         formHelper::fixArrays();
     }
     if (class_exists('csrfHelper')) {
         injector::register(array('csrfHelper', 'injector'));
     }
     if (is::ssl() && isset(config::$https_domain) && !isset(config::$http_domain)) {
         if (is::existset($_GET, 'r_domain')) {
             config::$http_domain = get::fulldomain($_GET['r_domain']);
         } else {
             config::$http_domain = get::fulldomain('www');
         }
     }
     session_start();
     if (config::$isolated_subdomains) {
         // find the domain
         $domain = isset(config::$http_domain) ? config::$http_domain : get::fulldomain();
         // kill any subdomain sessions that have been transfered to another subdomain
         $existing = array_keys($_SESSION);
         foreach ($existing as $d) {
             if (!is_array($_SESSION[$d])) {
                 continue;
             }
             if (array_key_exists('kill_munla_session', $_SESSION[$d]) && $_SESSION[$d]['kill_munla_session']) {
                 unset($_SESSION[$d]);
             }
         }
         // initialize and setup the session for this subdomain
         if (!array_key_exists($domain, $_SESSION)) {
             $_SESSION[$domain] = array();
         }
         munla::$session =& $_SESSION[$domain];
     } else {
         munla::$session =& $_SESSION;
     }
     if (class_exists('singleUseArray')) {
         if (!is::existset(munla::$session, 'MUNLA_SINGLE_USE')) {
             munla::$singleUse = new singleUseArray();
         } else {
             munla::$singleUse = unserialize(munla::$session['MUNLA_SINGLE_USE']);
         }
     }
     $route = get::route();
     if (is_array($route) && $route['controller'] == 'csrf' && $route['action'] == 'keepalive' && class_exists('csrfHelper') && is::existset($route, 'params') && count($route['params']) > 0) {
         if (isset($_POST['token'])) {
             echo csrfHelper::keepAlive($route['params'][0], $_POST['token']);
         }
         exit;
     }
     if (class_exists('user') && is_subclass_of('user', 'userBase')) {
         if (!is::existset(munla::$session, 'MUNLA_USER')) {
             munla::$session['MUNLA_USER'] = new userWrapper(new user());
         }
     }
     injector::start();
     if (class_exists('app') && is_callable(array('app', 'setup'))) {
         app::setup();
     }
     if (!isset(munla::$user) && is::existset(munla::$session, 'MUNLA_USER')) {
         munla::$user =& munla::$session['MUNLA_USER'];
     }
     if (!is::ajax()) {
         $submittedForm = formHelper::process();
         if (isset($submittedForm)) {
             formHelper::process($submittedForm);
         }
     }
     if (class_exists('app') && is_callable(array('app', 'start'))) {
         $route = app::start($route);
     }
     if ($route === null) {
         $route = array('controller' => 'index', 'action' => 'index', 'params' => null);
     }
     $controller = get::controller($route['controller']);
     if (!isset($controller) && $route['controller'] != 'index') {
         //push action to params, controller to action, and set controller to index and try again.
         if ($route['action'] != 'index') {
             if (!isset($route['params'])) {
                 $route['params'] = array();
             }
             array_unshift($route['params'], $route['action']);
         }
         $route['action'] = $route['controller'];
         $route['controller'] = 'index';
         $controller = get::controller('index');
     }
     $view = null;
     if (isset($controller)) {
         $action = $controller->getAction(array($route['action'], $route['params']));
         if (isset($action)) {
             try {
                 $viewParams = call_user_func_array(array($controller, $action['action']), $action['params']);
                 //various things could happen here...
                 if (!isset($viewParams)) {
                     $viewParams = array();
                 } elseif (!is_array($viewParams)) {
                     $viewParams = array($viewParams);
                 }
                 $view = get::view($route, $controller, $viewParams);
             } catch (SSLException $e) {
                 go::ssl(!is::ssl());
             } catch (PermissionException $e) {
                 munla::$nohistory = true;
                 if (isset(munla::$user) && !munla::$user->is_logged_in() && munla::$user->getLoginView()) {
                     $view = munla::$user->getLoginView();
                 } else {
                     $view = get::view('errors/generic', 'default', array('error_msg' => $e->getMessage()));
                 }
             } catch (Exception $e) {
                 munla::$nohistory = true;
                 $view = get::view('errors/generic', 'default', array('error_msg' => $e->getMessage()));
             }
         } else {
             $view = get::view($route, $controller);
         }
     } else {
         $view = get::view($route);
     }
     if ($view != null) {
         $view->render();
     } else {
         throw new Exception('View not found!');
     }
     if (class_exists('app', false)) {
         munla::$nohistory = app::finish(munla::$nohistory);
     }
     if (munla::$nohistory === false) {
         munla::$session['lastpage'] = get::url();
     }
     if (isset(munla::$singleUse)) {
         munla::$session['MUNLA_SINGLE_USE'] = serialize(munla::$singleUse);
     }
 }
Example #8
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;
 }
Example #9
0
 /**
  * Validates a given CSRF form submission.
  * 
  * @throws CSRFException when a POST form doesn't have a csrf field.
  * 
  * @return bool TRUE when CSRF token validates, false otherwise.
  */
 public static function validate_form()
 {
     self::removeExpiredTokens();
     if (count($_POST)) {
         if (!is::existset($_POST, 'csrf_token')) {
             throw new CSRFException('No CSRF form fields were found.');
         }
         return self::validate($_POST['csrf_token']);
     }
     return false;
 }
Example #10
0
 /**
  * Generates the HTML for the form element.
  * 
  * @return string
  */
 public function __toString()
 {
     $this->attributes['id'] = $this->getId();
     $this->attributes['name'] = $this->getName();
     $keyvalues = get::array_def($this->attributes, 'keyvalues', false, array(true, false));
     $placeholder = get::array_def($this->attributes, 'placeholder', '');
     $separator = get::array_def($this->attributes, 'separator', false);
     $value = get::array_def($this->attributes, 'value', array());
     $multiple = get::array_def($this->attributes, 'multiple', false) == 'multiple';
     if ($multiple && substr($this->attributes['name'], -2) != '[]') {
         $this->attributes['name'] .= '[]';
     }
     if (!is_array($value) && strlen(trim($value)) < 1) {
         $value = array();
     }
     if (!is_array($value)) {
         $value = array($value);
     }
     $html = sprintf('<select%s>', get::formattedAttributes($this->getAttributes()));
     if (!$multiple && isset($placeholder) && strlen(trim($placeholder)) > 0) {
         $html .= sprintf('<option value="%s" disabled%s>%s</option>', get::encodedAttribute($this->emptyValue), count($value) > 0 ? '' : ' selected', get::entities($placeholder));
         if (isset($separator) && $separator !== false) {
             $separator = $separator === true ? '---------------' : $separator;
             $html .= sprintf('<option value="%s" disabled>%s</option>', get::encodedAttribute($this->emptyValue), get::entities($separator));
         }
     }
     if (isset($this->list) && count($this->list) > 0) {
         $stack = $this->build_stack($this->list);
         while ($stack) {
             $current = array_shift($stack);
             if (!is_array($current)) {
                 $html .= $current;
                 continue;
             }
             if (is_array($current['value'])) {
                 if (!is_string($current['key'])) {
                     continue;
                 }
                 $substack = $this->build_stack($current['value']);
                 if ($substack) {
                     $html .= sprintf('<optgroup label="%s">', get::encodedAttribute($current['key']));
                     array_unshift($stack, '</optgroup>');
                     while ($substack) {
                         array_unshift($stack, array_pop($substack));
                     }
                 }
             } else {
                 $v = $keyvalues || is_string($current['key']) ? (string) $current['key'] : $current['value'];
                 $l = $current['value'];
                 $selected = '';
                 if ($l == '-') {
                     $l = !isset($separator) || is_bool($separator) ? '---------------' : $separator;
                     $v = $this->emptyValue;
                 } else {
                     $selected = in_array($v, $value) ? ' selected="selected"' : '';
                 }
                 $html .= sprintf('<option value="%s"%s>%s</option>', get::encodedAttribute($v), $selected, get::entities($l));
             }
         }
     }
     $html .= '</select>';
     if (is::existset($this->attributes, 'autofocus')) {
         $html .= $this->getAutoFocusScript($this->attributes['id']);
     }
     return $html;
 }
Example #11
0
 /**
  * Creates a new form element.
  * 
  * @param array $attributes The attributes that should be assigned to the input element.
  */
 public function __construct(array $attributes)
 {
     if (is::existset($attributes, 'id')) {
         $this->setId($attributes['id']);
     }
     if (is::existset($attributes, 'name')) {
         $this->setName($attributes['name']);
     }
     $this->attributes = $attributes;
 }
Example #12
0
 /**
  * Checks a given file array for errors.
  * 
  * @param array $file The fixed file array from $_FILES.
  * 
  * @return bool|string Returns boolean TRUE upon successfull validation, and an error message string upon failure.
  */
 private function checkFileForError(array &$file)
 {
     if (!in_array($file['error'], array(0, 4))) {
         switch ($file['error']) {
             case 1:
                 $return = 'The uploaded file(%1$s) exceeds the servers max filesize.';
                 break;
             case 2:
                 $return = 'The uploaded file(%1$s) exceeds the max filesize.';
                 break;
             case 3:
                 $return = 'The uploaded file(%1$s) was only partially uploaded.';
                 break;
             case 4:
                 $return = 'No file was uploaded.';
                 break;
             case 6:
                 $return = 'Missing a temporary folder.';
                 break;
             case 7:
                 $return = 'Failed to write file(%1$s) to disk.';
                 break;
             case 8:
                 $return = 'The uploaded file(%1$s) was stopped.';
                 break;
             default:
                 $return = 'Unknown file upload error (%2$d).';
                 break;
         }
         return sprintf($return, $file['name'], $file['error']);
     }
     if (is::existset($this->attributes, 'accept')) {
         $accepted = array_filter(array_map('trim', explode(',', $this->attributes['accept'])), 'strlen');
         $valid = false;
         foreach ($accepted as $mime) {
             if (substr_count($mime, '/') != 1 || substr($mime, -1) == '/' || substr($mime, 0, 1) == '/') {
                 continue;
             }
             if (substr($mime, -2) == '/*') {
                 //generic accepted value...
                 if (strncmp($file['type'], substr($mime, 0, -2), strlen($mime) - 2) === 0) {
                     $valid = true;
                     break;
                 }
             } else {
                 //specific value...
                 if ($file['type'] == $mime) {
                     $valid = true;
                     break;
                 }
             }
         }
         if (!$valid) {
             return sprintf('The uploaded file(%s) is not of an excepted file type.', $file['name']);
         }
     }
     return true;
 }