/**
  * Method to get the field input markup.
  *
  * @return  string   The field input markup.
  *
  * @since   11.1
  */
 protected function getInput()
 {
     // Initialize some field attributes.
     $format = $this->element['format'] ? (string) $this->element['format'] : '%Y-%m-%d';
     // Build the attributes array.
     $attributes = array();
     if ($this->element['size']) {
         $attributes['size'] = (int) $this->element['size'];
     }
     if ($this->element['maxlength']) {
         $attributes['maxlength'] = (int) $this->element['maxlength'];
     }
     if ($this->element['class']) {
         $attributes['class'] = (string) $this->element['class'];
     }
     if ((string) $this->element['readonly'] == 'true') {
         $attributes['readonly'] = 'readonly';
     }
     if ((string) $this->element['disabled'] == 'true') {
         $attributes['disabled'] = 'disabled';
     }
     if ($this->element['onchange']) {
         $attributes['onchange'] = (string) $this->element['onchange'];
     }
     // Handle the special case for "now".
     if (strtoupper($this->value) == 'NOW') {
         $this->value = strftime($format);
     }
     // Get some system objects.
     $config = Factory::getConfig();
     $user = Factory::getUser();
     // If a known filter is given use it.
     switch (strtoupper((string) $this->element['filter'])) {
         case 'SERVER_UTC':
             // Convert a date to UTC based on the server timezone.
             if ((int) $this->value) {
                 // Get a date object based on the correct timezone.
                 $date = Factory::getDate($this->value, 'UTC');
                 $date->setTimezone(new DateTimeZone($config->get('offset')));
                 // Transform the date string.
                 $this->value = $date->format('Y-m-d H:i:s', true, false);
             }
             break;
         case 'USER_UTC':
             // Convert a date to UTC based on the user timezone.
             if ((int) $this->value) {
                 // Get a date object based on the correct timezone.
                 $date = Factory::getDate($this->value, 'UTC');
                 $date->setTimezone(new DateTimeZone($user->getParam('timezone', $config->get('offset'))));
                 // Transform the date string.
                 $this->value = $date->format('Y-m-d H:i:s', true, false);
             }
             break;
     }
     return Html::_('calendar', $this->value, $this->name, $this->id, $format, $attributes);
 }
 /**
  * Allows the application to load a custom or default identity.
  *
  * The logic and options for creating this object are adequately generic for default cases
  * but for many applications it will make sense to override this method and create an identity,
  * if required, based on more specific needs.
  *
  * @param   JUser  $identity  An optional identity object. If omitted, the factory user is created.
  *
  * @return  JApplicationBase This method is chainable.
  *
  * @since   12.1
  */
 public function loadIdentity(User $identity = null)
 {
     $this->identity = $identity === null ? Factory::getUser() : $identity;
     return $this;
 }
 /**
  * Method to determine a hash for anti-spoofing variable names
  *
  * @param   boolean  $forceNew  If true, force a new token to be created
  *
  * @return  string  Hashed var name
  *
  * @since   11.1
  */
 public static function getFormToken($forceNew = false)
 {
     $user = Factory::getUser();
     $session = Factory::getSession();
     // TODO: Decouple from legacy JApplication class.
     if (is_callable(array('JApplication', 'getHash'))) {
         $hash = JApplication::getHash($user->get('id', 0) . $session->getToken($forceNew));
     } else {
         $hash = md5(Factory::getApplication()->get('secret') . $user->get('id', 0) . $session->getToken($forceNew));
     }
     return $hash;
 }
 /**
  * Displays a checked out icon.
  *
  * @param   object   &$row        A data object (must contain checkedout as a property).
  * @param   integer  $i           The index of the row.
  * @param   string   $identifier  The property name of the primary key or index of the row.
  *
  * @return  string
  *
  * @since   11.1
  */
 public static function checkedOut(&$row, $i, $identifier = 'id')
 {
     $user = Factory::getUser();
     $userid = $user->get('id');
     $result = false;
     if ($row instanceof Table) {
         $result = $row->isCheckedOut($userid);
     } else {
         $result = false;
     }
     $checked = '';
     if ($result) {
         $checked = self::_checkedOut($row);
     } else {
         if ($identifier == 'id') {
             $checked = Html::_('grid.id', $i, $row->{$identifier});
         } else {
             $checked = Html::_('grid.id', $i, $row->{$identifier}, $result, $identifier);
         }
     }
     return $checked;
 }
 /**
  * Returns a UL list of user groups with check boxes
  *
  * @param   string   $name             The name of the checkbox controls array
  * @param   array    $selected         An array of the checked boxes
  * @param   boolean  $checkSuperAdmin  If false only super admins can add to super admin groups
  *
  * @return  string
  *
  * @since   11.1
  */
 public static function usergroups($name, $selected, $checkSuperAdmin = false)
 {
     static $count;
     $count++;
     $isSuperAdmin = Factory::getUser()->authorise('core.admin');
     $db = Factory::getDbo();
     $query = $db->getQuery(true);
     $query->select('a.*, COUNT(DISTINCT b.id) AS level');
     $query->from($db->quoteName('#__usergroups') . ' AS a');
     $query->join('LEFT', $db->quoteName('#__usergroups') . ' AS b ON a.lft > b.lft AND a.rgt < b.rgt');
     $query->group('a.id, a.title, a.lft, a.rgt, a.parent_id');
     $query->order('a.lft ASC');
     $db->setQuery($query);
     $groups = $db->loadObjectList();
     $html = array();
     $html[] = '<ul class="checklist usergroups">';
     for ($i = 0, $n = count($groups); $i < $n; $i++) {
         $item =& $groups[$i];
         // If checkSuperAdmin is true, only add item if the user is superadmin or the group is not super admin
         if (!$checkSuperAdmin || $isSuperAdmin || !AuthorizationAccess::checkGroup($item->id, 'core.admin')) {
             // Setup  the variable attributes.
             $eid = $count . 'group_' . $item->id;
             // Don't call in_array unless something is selected
             $checked = '';
             if ($selected) {
                 $checked = in_array($item->id, $selected) ? ' checked="checked"' : '';
             }
             $rel = $item->parent_id > 0 ? ' rel="' . $count . 'group_' . $item->parent_id . '"' : '';
             // Build the HTML for the item.
             $html[] = '	<li>';
             $html[] = '		<input type="checkbox" name="' . $name . '[]" value="' . $item->id . '" id="' . $eid . '"';
             $html[] = '				' . $checked . $rel . ' />';
             $html[] = '		<label for="' . $eid . '">';
             $html[] = '		' . str_repeat('<span class="gi">|&mdash;</span>', $item->level) . $item->title;
             $html[] = '		</label>';
             $html[] = '	</li>';
         }
     }
     $html[] = '</ul>';
     return implode("\n", $html);
 }
 /**
  * Returns formated date according to a given format and time zone.
  *
  * @param   string   $input      String in a format accepted by date(), defaults to "now".
  * @param   string   $format     The date format specification string (see {@link PHP_MANUAL#date})
  * @param   mixed    $tz         Time zone to be used for the date.  Special cases: boolean true for user
  *                               setting, boolean false for server setting.
  * @param   boolean  $gregorian  True to use Gregorian calenar
  *
  * @return  string    A date translated by the given format and time zone.
  *
  * @see     strftime
  * @since   11.1
  */
 public static function date($input = 'now', $format = null, $tz = true, $gregorian = false)
 {
     // Get some system objects.
     $config = Factory::getConfig();
     $user = Factory::getUser();
     // UTC date converted to user time zone.
     if ($tz === true) {
         // Get a date object based on UTC.
         $date = Factory::getDate($input, 'UTC');
         // Set the correct time zone based on the user configuration.
         $date->setTimeZone(new DateTimeZone($user->getParam('timezone', $config->get('offset'))));
     } elseif ($tz === false) {
         // Get a date object based on UTC.
         $date = Factory::getDate($input, 'UTC');
         // Set the correct time zone based on the server configuration.
         $date->setTimeZone(new DateTimeZone($config->get('offset')));
     } elseif ($tz === null) {
         $date = Factory::getDate($input);
     } else {
         // Get a date object based on UTC.
         $date = Factory::getDate($input, 'UTC');
         // Set the correct time zone based on the server configuration.
         $date->setTimeZone(new DateTimeZone($tz));
     }
     // If no format is given use the default locale based format.
     if (!$format) {
         $format = Text::_('DATE_FORMAT_LC1');
     } elseif (Factory::getLanguage()->hasKey($format)) {
         $format = Text::_($format);
     }
     if ($gregorian) {
         return $date->format($format, true);
     } else {
         return $date->calendar($format, true);
     }
 }
 /**
  * Method to apply an input filter to a value based on field data.
  *
  * @param   string  $element  The XML element object representation of the form field.
  * @param   mixed   $value    The value to filter for the field.
  *
  * @return  mixed   The filtered value.
  *
  * @since   11.1
  */
 protected function filterField($element, $value)
 {
     // Make sure there is a valid SimpleXMLElement.
     if (!$element instanceof SimpleXMLElement) {
         return false;
     }
     // Get the field filter type.
     $filter = (string) $element['filter'];
     // Process the input value based on the filter.
     $return = null;
     switch (strtoupper($filter)) {
         // Access Control Rules.
         case 'RULES':
             $return = array();
             foreach ((array) $value as $action => $ids) {
                 // Build the rules array.
                 $return[$action] = array();
                 foreach ($ids as $id => $p) {
                     if ($p !== '') {
                         $return[$action][$id] = $p == '1' || $p == 'true' ? true : false;
                     }
                 }
             }
             break;
             // Do nothing, thus leaving the return value as null.
         // Do nothing, thus leaving the return value as null.
         case 'UNSET':
             break;
             // No Filter.
         // No Filter.
         case 'RAW':
             $return = $value;
             break;
             // Filter the input as an array of integers.
         // Filter the input as an array of integers.
         case 'INT_ARRAY':
             // Make sure the input is an array.
             if (is_object($value)) {
                 $value = get_object_vars($value);
             }
             $value = is_array($value) ? $value : array($value);
             ArrayHelper::toInteger($value);
             $return = $value;
             break;
             // Filter safe HTML.
         // Filter safe HTML.
         case 'SAFEHTML':
             $return = Input::getInstance(null, null, 1, 1)->clean($value, 'string');
             break;
             // Convert a date to UTC based on the server timezone offset.
         // Convert a date to UTC based on the server timezone offset.
         case 'SERVER_UTC':
             if ((int) $value > 0) {
                 // Get the server timezone setting.
                 $offset = Factory::getConfig()->get('offset');
                 // Return an SQL formatted datetime string in UTC.
                 $return = Factory::getDate($value, $offset)->toSql();
             } else {
                 $return = '';
             }
             break;
             // Convert a date to UTC based on the user timezone offset.
         // Convert a date to UTC based on the user timezone offset.
         case 'USER_UTC':
             if ((int) $value > 0) {
                 // Get the user timezone setting defaulting to the server timezone setting.
                 $offset = Factory::getUser()->getParam('timezone', Factory::getConfig()->get('offset'));
                 // Return a MySQL formatted datetime string in UTC.
                 $return = Factory::getDate($value, $offset)->toSql();
             } else {
                 $return = '';
             }
             break;
             // Ensures a protocol is present in the saved field. Only use when
             // the only permitted protocols requre '://'. See JFormRuleUrl for list of these.
         // Ensures a protocol is present in the saved field. Only use when
         // the only permitted protocols requre '://'. See JFormRuleUrl for list of these.
         case 'URL':
             if (empty($value)) {
                 return;
             }
             $value = Input::getInstance()->clean($value, 'html');
             $value = trim($value);
             // Check for a protocol
             $protocol = parse_url($value, PHP_URL_SCHEME);
             // If there is no protocol and the relative option is not specified,
             // we assume that it is an external URL and prepend http://.
             if ($element['type'] == 'url' && !$protocol && !$element['relative'] || !$element['type'] == 'url' && !$protocol) {
                 $protocol = 'http';
                 // If it looks like an internal link, then add the root.
                 if (substr($value, 0) == 'index.php') {
                     $value = Uri::root() . $value;
                 }
                 // Otherwise we treat it is an external link.
                 // Put the url back together.
                 $value = $protocol . '://' . $value;
             } elseif (!$protocol && $element['relative']) {
                 $host = Uri::getInstance('SERVER')->gethost();
                 // If it starts with the host string, just prepend the protocol.
                 if (substr($value, 0) == $host) {
                     $value = 'http://' . $value;
                 } else {
                     $value = Uri::root() . $value;
                 }
             }
             $return = $value;
             break;
         case 'TEL':
             $value = trim($value);
             // Does it match the NANP pattern?
             if (preg_match('/^(?:\\+?1[-. ]?)?\\(?([2-9][0-8][0-9])\\)?[-. ]?([2-9][0-9]{2})[-. ]?([0-9]{4})$/', $value) == 1) {
                 $number = (string) preg_replace('/[^\\d]/', '', $value);
                 if (substr($number, 0, 1) == 1) {
                     $number = substr($number, 1);
                 }
                 if (substr($number, 0, 2) == '+1') {
                     $number = substr($number, 2);
                 }
                 $result = '1.' . $number;
             } elseif (preg_match('/^\\+(?:[0-9] ?){6,14}[0-9]$/', $value) == 1) {
                 $countrycode = substr($value, 0, strpos($value, ' '));
                 $countrycode = (string) preg_replace('/[^\\d]/', '', $countrycode);
                 $number = strstr($value, ' ');
                 $number = (string) preg_replace('/[^\\d]/', '', $number);
                 $result = $countrycode . '.' . $number;
             } elseif (preg_match('/^\\+[0-9]{1,3}\\.[0-9]{4,14}(?:x.+)?$/', $value) == 1) {
                 if (strstr($value, 'x')) {
                     $xpos = strpos($value, 'x');
                     $value = substr($value, 0, $xpos);
                 }
                 $result = str_replace('+', '', $value);
             } elseif (preg_match('/[0-9]{1,3}\\.[0-9]{4,14}$/', $value) == 1) {
                 $result = $value;
             } else {
                 $value = (string) preg_replace('/[^\\d]/', '', $value);
                 if ($value != null && strlen($value) <= 15) {
                     $length = strlen($value);
                     // If it is fewer than 13 digits assume it is a local number
                     if ($length <= 12) {
                         $result = '.' . $value;
                     } else {
                         // If it has 13 or more digits let's make a country code.
                         $cclen = $length - 12;
                         $result = substr($value, 0, $cclen) . '.' . substr($value, $cclen);
                     }
                 } else {
                     $result = '';
                 }
             }
             $return = $result;
             break;
         default:
             // Check for a callback filter.
             if (strpos($filter, '::') !== false && is_callable(explode('::', $filter))) {
                 $return = call_user_func(explode('::', $filter), $value);
             } elseif (function_exists($filter)) {
                 $return = call_user_func($filter, $value);
             } else {
                 $return = Input::getInstance()->clean($value, $filter);
             }
             break;
     }
     return $return;
 }
 /**
  * Method to save the JUser object to the database
  *
  * @param   boolean  $updateOnly  Save the object only if not a new user
  *                                Currently only used in the user reset password method.
  *
  * @return  boolean  True on success
  *
  * @since   11.1
  * @throws  RuntimeException
  */
 public function save($updateOnly = false)
 {
     // Create the user table object
     $table = $this->getTable();
     $this->params = (string) $this->_params;
     $table->bind($this->getProperties());
     // Allow an exception to be thrown.
     try {
         // Check and store the object.
         if (!$table->check()) {
             $this->setError($table->getError());
             return false;
         }
         // If user is made a Super Admin group and user is NOT a Super Admin
         // @todo ACL - this needs to be acl checked
         $my = Factory::getUser();
         // Are we creating a new user
         $isNew = empty($this->id);
         // If we aren't allowed to create new users return
         if ($isNew && $updateOnly) {
             return true;
         }
         // Get the old user
         $oldUser = new User($this->id);
         // Access Checks
         // The only mandatory check is that only Super Admins can operate on other Super Admin accounts.
         // To add additional business rules, use a user plugin and throw an Exception with onUserBeforeSave.
         // Check if I am a Super Admin
         $iAmSuperAdmin = $my->authorise('core.admin');
         // We are only worried about edits to this account if I am not a Super Admin.
         if ($iAmSuperAdmin != true) {
             if ($isNew) {
                 // Check if the new user is being put into a Super Admin group.
                 foreach ($this->groups as $groupId) {
                     if (Access::checkGroup($groupId, 'core.admin')) {
                         throw new RuntimeException('User not Super Administrator');
                     }
                 }
             } else {
                 // I am not a Super Admin, and this one is, so fail.
                 if (Access::check($this->id, 'core.admin')) {
                     throw new RuntimeException('User not Super Administrator');
                 }
                 if ($this->groups != null) {
                     // I am not a Super Admin and I'm trying to make one.
                     foreach ($this->groups as $groupId) {
                         if (Access::checkGroup($groupId, 'core.admin')) {
                             throw new RuntimeException('User not Super Administrator');
                         }
                     }
                 }
             }
         }
         // Fire the onUserBeforeSave event.
         PluginHelper::importPlugin('user');
         $dispatcher = Dispatcher::getInstance();
         $result = $dispatcher->trigger('onUserBeforeSave', array($oldUser->getProperties(), $isNew, $this->getProperties()));
         if (in_array(false, $result, true)) {
             // Plugin will have to raise its own error or throw an exception.
             return false;
         }
         // Store the user data in the database
         $result = $table->store();
         // Set the id for the JUser object in case we created a new user.
         if (empty($this->id)) {
             $this->id = $table->get('id');
         }
         if ($my->id == $table->id) {
             $registry = new Registry();
             $registry->loadString($table->params);
             $my->setParameters($registry);
         }
         // Fire the onUserAfterSave event
         $dispatcher->trigger('onUserAfterSave', array($this->getProperties(), $isNew, $result, $this->getError()));
     } catch (Exception $e) {
         $this->setError($e->getMessage());
         return false;
     }
     return $result;
 }
 /**
  * Gets the user profile information
  *
  * @param   integer  $userId  The id of the user.
  *
  * @return  object
  *
  * @since   11.1
  */
 public static function getProfile($userId = 0)
 {
     if ($userId == 0) {
         $user = Factory::getUser();
         $userId = $user->id;
     }
     // Get the dispatcher and load the user's plugins.
     $dispatcher = Dispatcher::getInstance();
     Helper::importPlugin('user');
     $data = new Object();
     $data->id = $userId;
     // Trigger the data preparation event.
     $dispatcher->trigger('onContentPrepareData', array('com_users.profile', &$data));
     return $data;
 }
 /**
  * Returns a published state on a grid
  *
  * @param   integer       $value         The state value.
  * @param   integer       $i             The row index
  * @param   string|array  $prefix        An optional task prefix or an array of options
  * @param   boolean       $enabled       An optional setting for access control on the action.
  * @param   string        $checkbox      An optional prefix for checkboxes.
  * @param   string        $publish_up    An optional start publishing date.
  * @param   string        $publish_down  An optional finish publishing date.
  *
  * @return  string  The Html code
  *
  * @see     JHtmlJGrid::state
  * @since   11.1
  */
 public static function published($value, $i, $prefix = '', $enabled = true, $checkbox = 'cb', $publish_up = null, $publish_down = null)
 {
     if (is_array($prefix)) {
         $options = $prefix;
         $enabled = array_key_exists('enabled', $options) ? $options['enabled'] : $enabled;
         $checkbox = array_key_exists('checkbox', $options) ? $options['checkbox'] : $checkbox;
         $prefix = array_key_exists('prefix', $options) ? $options['prefix'] : '';
     }
     $states = array(1 => array('unpublish', 'JPUBLISHED', 'JLIB_HTML_UNPUBLISH_ITEM', 'JPUBLISHED', false, 'publish', 'publish'), 0 => array('publish', 'JUNPUBLISHED', 'JLIB_HTML_PUBLISH_ITEM', 'JUNPUBLISHED', false, 'unpublish', 'unpublish'), 2 => array('unpublish', 'JARCHIVED', 'JLIB_HTML_UNPUBLISH_ITEM', 'JARCHIVED', false, 'archive', 'archive'), -2 => array('publish', 'JTRASHED', 'JLIB_HTML_PUBLISH_ITEM', 'JTRASHED', false, 'trash', 'trash'));
     // Special state for dates
     if ($publish_up || $publish_down) {
         $nullDate = Factory::getDBO()->getNullDate();
         $nowDate = Factory::getDate()->toUnix();
         $tz = new DateTimeZone(Factory::getUser()->getParam('timezone', Factory::getConfig()->get('offset')));
         $publish_up = $publish_up != $nullDate ? Factory::getDate($publish_up, 'UTC')->setTimeZone($tz) : false;
         $publish_down = $publish_down != $nullDate ? Factory::getDate($publish_down, 'UTC')->setTimeZone($tz) : false;
         // Create tip text, only we have publish up or down settings
         $tips = array();
         if ($publish_up) {
             $tips[] = Text::sprintf('JLIB_HTML_PUBLISHED_START', $publish_up->format(Date::$format, true));
         }
         if ($publish_down) {
             $tips[] = Text::sprintf('JLIB_HTML_PUBLISHED_FINISHED', $publish_down->format(Date::$format, true));
         }
         $tip = empty($tips) ? false : implode('<br/>', $tips);
         // Add tips and special titles
         foreach ($states as $key => $state) {
             // Create special titles for published items
             if ($key == 1) {
                 $states[$key][2] = $states[$key][3] = 'JLIB_HTML_PUBLISHED_ITEM';
                 if ($publish_up > $nullDate && $nowDate < $publish_up->toUnix()) {
                     $states[$key][2] = $states[$key][3] = 'JLIB_HTML_PUBLISHED_PENDING_ITEM';
                     $states[$key][5] = $states[$key][6] = 'pending';
                 }
                 if ($publish_down > $nullDate && $nowDate > $publish_down->toUnix()) {
                     $states[$key][2] = $states[$key][3] = 'JLIB_HTML_PUBLISHED_EXPIRED_ITEM';
                     $states[$key][5] = $states[$key][6] = 'expired';
                 }
             }
             // Add tips to titles
             if ($tip) {
                 $states[$key][1] = Text::_($states[$key][1]);
                 $states[$key][2] = Text::_($states[$key][2]) . '::' . $tip;
                 $states[$key][3] = Text::_($states[$key][3]) . '::' . $tip;
                 $states[$key][4] = true;
             }
         }
         return self::state($states, $value, $i, array('prefix' => $prefix, 'translate' => !$tip), $enabled, true, $checkbox);
     }
     return self::state($states, $value, $i, $prefix, $enabled, true, $checkbox);
 }
 /**
  * Loads the published plugins.
  *
  * @return  array  An array of published plugins
  *
  * @since   11.1
  */
 protected static function _load()
 {
     if (self::$plugins !== null) {
         return self::$plugins;
     }
     $user = Factory::getUser();
     $cache = Factory::getCache('com_plugins', '');
     $levels = implode(',', $user->getAuthorisedViewLevels());
     if (!(self::$plugins = $cache->get($levels))) {
         $db = Factory::getDbo();
         $query = $db->getQuery(true);
         $query->select('folder AS type, element AS name, params')->from('#__extensions')->where('enabled >= 1')->where('type =' . $db->Quote('plugin'))->where('state >= 0')->where('access IN (' . $levels . ')')->order('ordering');
         self::$plugins = $db->setQuery($query)->loadObjectList();
         $cache->store(self::$plugins, $levels);
     }
     return self::$plugins;
 }