Esempio n. 1
0
 /**
  * Validates a number value.
  * 
  * @param string $value The value to validate.
  * 
  * @return bool|string Returns boolean TRUE upon successfull validation, and an error message string upon failure.
  */
 public function validate(&$value)
 {
     $required = get::array_def($this->attributes, 'required', false) == 'required';
     $integeronly = get::array_def($this->attributes, 'integeronly', false, array(true, false));
     $msglbl = get::array_def($this->attributes, 'msglbl', get::array_def($this->attributes, 'name', $this->getId()));
     if ($required && (!isset($value) || strlen(trim($value)) < 1)) {
         return sprintf('"%s" is a required field.', $msglbl);
     }
     if (isset($value) && strlen(trim($value)) > 0) {
         $value = trim($value);
         $valid = $integeronly ? preg_match('/^[+-]?\\d+$/', $value) ? (int) $value : false : is::float($value);
         $errorText = $integeronly ? 'integer' : 'number';
         $min = get::array_def($this->attributes, 'min', null);
         $max = get::array_def($this->attributes, 'max', null);
         if ($valid === false) {
             return sprintf('"%s" is not a valid %s.', $msglbl, $errorText);
         } elseif (isset($min) && $valid < $min) {
             return sprintf('"%s" is not allowed to be less than %s.', $msglbl, $min);
         } elseif (isset($max) && $valid > $max) {
             return sprintf('"%s" is not allowed to be greater than %s.', $msglbl, $max);
         }
         $value = $valid;
     }
     return true;
 }
Esempio n. 2
0
 public final function render()
 {
     $this->lf = $this->layout !== null ? get::mvc_file('layout', $this->layout) : false;
     if ($this->lf === false && $this->layout != 'default') {
         $this->lf = get::mvc_file('layout', 'default');
     }
     $this->vf = $this->view !== null ? get::mvc_file('view', $this->view) : false;
     if ($this->lf === false) {
         throw new Exception('Unable to find layout: ' . $this->layout);
     }
     if ($this->vf === false) {
         throw new Exception('Unable to find view: ' . $this->view);
     }
     if (isset($this->params) && is_array($this->params) && is::assoc_array($this->params)) {
         extract($this->params);
     }
     $this->helpers = get::helpers('template');
     extract($this->helpers);
     ob_start();
     require $this->vf;
     $munla_view_data = ob_get_contents();
     ob_end_clean();
     if (!isset($page_title)) {
         $page_title = config::TITLE_DEFAULT;
     }
     if (!isset($page_class)) {
         $page_class = preg_replace('[^a-zA-Z0-9-_]', '', str_replace('/', '-', $this->view));
     }
     require $this->lf;
 }
Esempio n. 3
0
File: go.php Progetto: 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;
 }
Esempio n. 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['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;
 }
Esempio n. 5
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;
 }
Esempio n. 6
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;
 }
Esempio n. 7
0
 /**
  * Validates a datetime value.
  * 
  * @param string $value The value to validate.
  * 
  * @return bool|string Returns boolean TRUE upon successfull validation, and an error message string upon failure.
  */
 public function validate(&$value)
 {
     $return = parent::validate($value);
     if ($return !== true) {
         return $return;
     }
     if (isset($value) && strlen(trim($value)) > 0) {
         $msglbl = get::array_def($this->attributes, 'msglbl', get::array_def($this->attributes, 'name', $this->getId()));
         $valid = is::datetime($value);
         if ($valid === false) {
             return sprintf('"%s" does not have a valid date/time. The format is YYYY-mm-ddThh:mm:ss.fff. "T" is a literal separator.', $msglbl);
         }
         $mode = get::array_def($this->attributes, 'datemode', 'html');
         $min = get::array_def($this->attributes, 'min', false);
         if (is_object($min) && $min instanceof cDateTime) {
             if ($valid->lessThan($min)) {
                 switch ($mode) {
                     case 'html':
                         break;
                     case 'us':
                         $min = $min->format_us();
                         break;
                     default:
                         $min = $min->format($mode);
                         break;
                 }
                 return sprintf('"%s" cannot be before "%s".', $msglbl, $min);
             }
         }
         $max = get::array_def($this->attributes, 'max', false);
         if (is_object($max) && $max instanceof cDateTime) {
             if ($max->lessThan($valid)) {
                 switch ($mode) {
                     case 'html':
                         break;
                     case 'us':
                         $max = $max->format_us();
                         break;
                     default:
                         $max = $max->format($mode);
                         break;
                 }
                 return sprintf('"%s" cannot be after "%s".', $msglbl, $max);
             }
         }
         $value = $valid;
     }
     return true;
 }
Esempio n. 8
0
 /**
  * Creates the HTML for the datalist element.
  * 
  * @return string
  */
 public function __toString()
 {
     $html = sprintf('<datalist id="%s">', get::encodedAttribute($this->getId()));
     if (is::assoc_array($this->list)) {
         foreach ($this->list as $value => $lbl) {
             $html .= sprintf('<option label="%s" value="%s" />', get::encodedAttribute($lbl), get::encodedAttribute($value));
         }
     } else {
         foreach ($this->list as $value) {
             $html .= sprintf('<option value="%s" />', get::encodedAttribute($value));
         }
     }
     $html .= '</datalist>';
     return $html;
 }
Esempio n. 9
0
File: url.php Progetto: Borvik/Munla
 /**
  * Validates a url value.
  * 
  * @param string $value The value to validate.
  * 
  * @return bool|string Returns boolean TRUE upon successfull validation, and an error message string upon failure.
  */
 public function validate(&$value)
 {
     $return = parent::validate($value);
     if ($return !== true) {
         return $return;
     }
     if (isset($value) && strlen(trim($value)) > 0) {
         $valid = is::url($value, true);
         if (!is_array($valid)) {
             $msglbl = get::array_def($this->attributes, 'msglbl', get::array_def($this->attributes, 'name', $this->getId()));
             return sprintf('"%s" has an invalid url. Urls start with http/https/ftp followed by "://" and then the domain and path.', $msglbl);
         }
         $value = $valid;
     }
     return true;
 }
Esempio n. 10
0
 /**
  * Validates a email value.
  * 
  * @param string $value The value to validate.
  * 
  * @return bool|string Returns boolean TRUE upon successfull validation, and an error message string upon failure.
  */
 public function validate(&$value)
 {
     $return = parent::validate($value);
     if ($return !== true) {
         return $return;
     }
     if (isset($value) && strlen(trim($value)) > 0) {
         $valid = is::email($value, get::array_def($this->attributes, 'multiple', false) == 'multiple');
         if (!is_object($valid) || !($valid instanceof emailAddressList || $valid instanceof emailAddress)) {
             $msglbl = get::array_def($this->attributes, 'msglbl', get::array_def($this->attributes, 'name', $this->getId()));
             return sprintf('"%s" has an invalid email address.', $msglbl);
         }
         $value = $valid;
     }
     return true;
 }
Esempio n. 11
0
 /**
  * Validates a color value.  According to the W3C this field should ALWAYS have a value.
  * 
  * @param string $value The value to validate.
  * 
  * @return bool|string Returns boolean TRUE upon successfull validation, and an error message string upon failure.
  */
 public function validate(&$value)
 {
     $return = parent::validate($value);
     if ($return !== true) {
         return $return;
     }
     if (!isset($value) || strlen(trim($value)) < 1) {
         $value = '#000000';
     }
     if (isset($value) && strlen(trim($value)) > 0) {
         $valid = is::color($value);
         if ($valid === false) {
             $msglbl = get::array_def($this->attributes, 'msglbl', get::array_def($this->attributes, 'name', $this->getId()));
             return sprintf('"%s" has an invalid color (ex. #FFFFFF).', $msglbl);
         }
         $value = $valid;
     }
     return true;
 }
Esempio n. 12
0
assertIdentical(is::is_kana_utf8('アあ'), false);
//
assertIdentical(is::is_kana_utf8('あ'), true);
assertIdentical(is::is_kana_utf8('あいう'), true);
assertIdentical(is::is_kana_utf8('あーん'), true);
// ドメイン
assertIdentical(is::is_domain('test.com'), true);
assertIdentical(is::is_domain('www.hogehoge.jp'), true);
assertIdentical(is::is_domain('www.hoge-hoge.jp'), true);
//
assertIdentical(is::is_domain('www.hogehoge.jp.'), false);
// …微妙だけどねぇ
assertIdentical(is::is_domain('www..hogehoge.jp'), false);
assertIdentical(is::is_domain('www.hoge_hoge.jp'), false);
assertIdentical(is::is_domain('www.hoge&%$#"hoge.jp'), false);
// メアド
assertIdentical(is::is_email('*****@*****.**'), true);
assertIdentical(is::is_email('*****@*****.**'), true);
assertIdentical(is::is_email('*****@*****.**'), true);
assertIdentical(is::is_email('*****@*****.**'), true);
assertIdentical(is::is_email('"hoge@aaa+test"@aa.jp'), true);
assertIdentical(is::is_email('*****@*****.**'), true);
assertIdentical(is::is_email('"><script>alert(\'or/**/1=1#\')</script>"@example.jp'), true);
assertIdentical(is::is_email('"><script>alert(\'or 1=1#\')</script>"@example.jp'), true);
//
assertIdentical(is::is_email('hoge@1.2.3.4'), false);
assertIdentical(is::is_email('hoge@ho_ge.com'), false);
assertIdentical(is::is_email('hoge@ho_ge'), false);
assertIdentical(is::is_email('@hoge.com'), false);
assertIdentical(is::is_email('hoge@'), false);
Esempio n. 13
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;
 }
Esempio n. 14
0
 public function forgot()
 {
     $email = $this->request->post('email');
     $type = $this->request->post('type');
     if (empty($email) || empty($type)) {
         return false;
     }
     switch ($type) {
         case 'email':
             if (!is::email($email)) {
                 return false;
             }
             $sql = 'SELECT id,code FROM UserLogin WHERE email=:id';
             break;
         case 'phone':
             if (!is::phone($email)) {
                 return false;
             }
             $sql = 'SELECT id,code FROM UserLogin WHERE phone=:id';
             break;
         default:
             return false;
     }
 }
Esempio n. 15
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;
 }
Esempio n. 16
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;
 }
Esempio n. 17
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;
 }
Esempio n. 18
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;
 }
Esempio n. 19
0
 /**
  * Checks the access permission for the given method name.  Checks SSL context, and user permission.
  * 
  * @param string $name The method the check.
  * 
  * @throws SSLException|PermissionException when access permission is invalid.
  * 
  * @return void
  */
 public function check_permission($name)
 {
     //first ignore some functions for some classes
     if (is_subclass_of($this->internal, 'controller') && $name == 'getAction') {
         return;
     }
     //check SSL access
     $ssl = $this->internal->getSSL();
     if (isset($ssl)) {
         if (is_bool($ssl) && $ssl != is::ssl() || is_array($ssl) && array_key_exists($name, $ssl) && is_bool($ssl[$name]) && $ssl[$name] != is::ssl()) {
             throw new SSLException(sprintf('Invalid context to run "%s" on %s.  Must be %sssl.', $name, get_class($this->internal), $ssl ? '' : 'non-'));
         }
     }
     //check permission access
     $access = $this->internal->getAccess();
     if (is_array($access) && array_key_exists($name, $access) && isset($access[$name])) {
         $ret = munla::$user->hasPermission($access[$name]);
         if (is_string($ret)) {
             throw new PermissionException($ret);
         } elseif ($ret === false) {
             throw new PermissionException(sprintf('Invalid permissions to run "%s" on %s.', $name, get_class($this->internal)));
         }
     }
 }
Esempio n. 20
0
File: is.php Progetto: Borvik/Munla
 /**
  * Checks to see if the given input is a valid date/time according to the HTML5
  * specifications used for datetime fields.
  * 
  * See http://dev.w3.org/html5/spec/common-microsyntaxes.html#dates
  *  for the rules on parsing dates
  * 
  * @param string $input
  *   The value to check.
  * 
  * @return mixed
  *   Returns a boolean false if the input is not a time, otherwise it
  *   returns an array with the following keys.
  *   - year: The numeric year.
  *   - month: The numeric month.
  *   - day: The numeric day.
  *   - formatted: US formatted date string m/d/y.
  *   - hour: The numeric hour in 24 notation.
  *   - minute: The numeric minute.
  *   - second: The numeric second.
  *   - faction: The numeric fraction of a second.
  *   - meridiem: AM/PM
  *   - format24: The formatted time using 24 hour notation.
  *   - format12: The formatted time using 12 hour notation without the meridiem.
  *   - unixdatetime: The unix datetimestamp as created by mktime.
  *   - datetime: A DateTime class containing the date/time.
  *   - isutc: Boolean indicating whether the time is UTC(Zulu) time or not.
  */
 public static function datetime($input, $local = false)
 {
     if (!isset($input)) {
         return false;
     }
     $in = trim($input);
     if (substr_count($in, 'T') != 1) {
         return false;
     }
     list($datepart, $timepart) = explode('T', $in);
     $dateValid = is::date($datepart);
     if ($dateValid === false) {
         return false;
     }
     $timeValid = is::time($timepart);
     if ($timeValid === false) {
         return false;
     }
     $timeValid->setDate($dateValid->format('Y'), $dateValid->format('m'), $dateValid->format('d'));
     return new cDateTime($timeValid, $local === true ? cDateTime::DATETIMELOCAL_KIND : cDateTime::DATETIME_KIND);
 }
Esempio n. 21
0
 public function __toString()
 {
     if (isset($this->params) && is_array($this->params) && is::assoc_array($this->params)) {
         extract($this->params);
     }
     $this->helpers = get::helpers('template');
     if (count($this->helpers) > 0) {
         extract($this->helpers);
     }
     ob_start();
     require $this->file;
     $data = ob_get_contents();
     ob_end_clean();
     return $data;
 }
Esempio n. 22
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);
     }
 }
Esempio n. 23
0
 public function &cache($value = null, &$result = null)
 {
     if (!isset($this->cache)) {
         $this->cache = new ModelCacheStorage();
     }
     $num_args = func_num_args();
     if ($num_args == 1) {
         //store the cache
         if (is_array($value)) {
             foreach ($value as $v) {
                 if (!is::model($v)) {
                     trigger_error('Array must contain only models');
                 }
             }
         } elseif (!is::model($value)) {
             trigger_error(sprintf('Argument 1 must be an %s of %s "model"', is_object($value) ? 'instance' : 'object', is_object($value) ? '' : 'class '), E_USER_ERROR);
         }
         $keys = $this->cache_keys();
         if (count($keys) > 0) {
             $avalue = is_array($value) ? $value : array($value);
             foreach ($avalue as $v) {
                 foreach ($keys as $key) {
                     if (is_array($key)) {
                         //compound key
                         $ck = new StdClass();
                         foreach ($key as $k) {
                             if (!isset($v->{$k})) {
                                 throw new Exception(sprintf('Property %s does not exist.', $k));
                             }
                             $ck->{$k} = $v->{$k};
                         }
                         $this->cache->attach($ck, $v);
                     } else {
                         if (!isset($v->{$key})) {
                             throw new Exception(sprintf('Property %s does not exist.', $key));
                         }
                         $ck = new StdClass();
                         $ck->{$key} = $v->{$key};
                         $this->cache->attach($ck, $v);
                     }
                 }
             }
         } else {
             trigger_error('Unable to cache model, cache_keys() does not containing any keys to index.', E_USER_ERROR);
         }
         return $value;
     } elseif ($num_args == 2) {
         //get the cache
         if (!is_array($value)) {
             trigger_error('Argument 1 must be an array', E_USER_ERROR);
         }
         $ck = new StdClass();
         foreach ($value as $k => $v) {
             $ck->{$k} = $v;
         }
         $result = false;
         if ($this->cache->offsetExists($ck)) {
             $result = $this->cache[$ck];
             $r = true;
             return $r;
         }
         return $result;
     } else {
         trigger_error(sprintf('Incorrect number of arguments received. Expected 1 or 2, got %s.', $num_args));
     }
 }
Esempio n. 24
0
File: get.php Progetto: Borvik/Munla
 /**
  * Attempts to construct the full URL for the given file.
  * 
  * Files that match a url (begin with http, ftp, or https followed by
  * ://) will be returned as is.
  * Files that appear to be a url (start with www.) will have the
  * current scheme prepended to them.
  * 
  * All others will be checked to see if the file exists relative to
  * the document root, and the current URL directory (request came from
  * http://www.mysite.com/path/two/otherfile.php then it would check 
  * both relative to http://www.mysite.com/path/two/ and http://www.mysite.com/.
  * If the file exists and is within the document root (can't have anyone
  * accessing system files using ../../ patterns) it will return the url
  * to the file.
  * 
  * If it cannot match as a URL or a valid file, it returns the passed
  * file exactly as it is.
  * 
  * Example:
  * Called from - http://www.mysite.com/path/file.php
  * File exists - http://www.mysite.com/css/layout.css
  * File exists - /var/systemfile (/var/www being the document root)
  * $file -> $return
  * css/layout.css -> http://www.mysite.com/css/layout.css
  * ../css/layout.css -> http://www.mysite.com/css/layout.css
  * http://www.othersite.com/file.pdf -> http://www.othersite.com/file.pdf
  * www.otheriste.com/file.pdf -> http://www.othersite.com/file.pdf
  * ../../systemfile -> systemfile (would result it broken link)
  * css/notthere.css -> css/notthere.css
  * 
  * @param string $file
  *   The file to create the URL for.
  * 
  * @return string
  *   The full URL of the file specified or the filename as given.
  *   If outside the server document root, the filename only.
  */
 public static function cache_file_url($file)
 {
     if (preg_match('/^(http|ftp|https):\\/\\//', $file)) {
         return $file;
     }
     if (strlen($file) > 4 && strtolower(substr($file, 0, 4)) == 'www.') {
         return 'http' . (is::ssl() ? 's' : '') . '://' . $file;
     }
     $docroot = strtr($_SERVER['DOCUMENT_ROOT'], '\\', '/');
     $self = strtr($_SERVER['PHP_SELF'], '\\', '/');
     if (substr($docroot, -1) != '/') {
         $docroot .= '/';
     }
     if (substr($self, 0, 1) == '/') {
         $self = substr($self, 1);
     }
     $base_dir = get::dirname($docroot . $self);
     if (substr($base_dir, -1) != '/') {
         $base_dir .= '/';
     }
     if (strlen($file) > strlen($docroot) && strtolower(substr($file, 0, strlen($docroot))) == strtolower($docroot)) {
         $file = substr($file, strlen($docroot));
     }
     //try relative (from basename of URL file, and server docroot)
     if (file_exists($base_dir . $file) || file_exists($docroot . $file)) {
         $path = get::realpath(file_exists($base_dir . $file) ? $base_dir . $file : $docroot . $file);
         if ($path !== false && strtolower(substr($path, 0, strlen($docroot))) == strtolower($docroot)) {
             //file is within the website
             $self_url = self::url();
             if ($self_url == null) {
                 define('DEBUG_URL', true);
                 $self_url = self::url();
                 log::debug($self_url);
                 define('URL_DEBUGGED', true);
             }
             $current = parse_url($self_url);
             $temp = '';
             if (isset($current['user']) && isset($current['pass'])) {
                 $temp .= sprintf('%s:%s@', $current['user'], $current['pass']);
             }
             $temp .= $current['host'];
             if (isset($current['port'])) {
                 $temp .= ':' . $current['port'];
             }
             return $current['scheme'] . '://' . str_replace('//', '/', $temp . '/' . substr($path, strlen($docroot)));
         } else {
             //file is outside of the website - hacking attempt
             return basename($file);
         }
     }
     return $file;
 }
Esempio n. 25
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;
 }