public function getBattleNetUrl() { $uri = new JUri(); $uri->setScheme($this->params->get('scheme', 'http')); $uri->setHost($this->params->get('region') . '.battle.net'); $uri->setPath('/wow/' . $this->params->get('locale') . '/guild/' . rawurlencode($this->params->get('realm')) . '/' . rawurlencode($this->params->get('guild')) . '/'); return $uri->toString(); }
/** * @param JUri $uri * * @throws RuntimeException * * @return mixed */ protected function getRemote($uri, $persistent = false) { $uri->setScheme('https'); $uri->setHost('www.warcraftlogs.com'); $this->url = $uri->toString(); $result = parent::getRemote($this->url, $persistent); $result->body = json_decode($result->body); if ($result->code != 200) { // hide api key from normal users if (!JFactory::getUser()->get('isRoot')) { $uri->delVar('api_key'); $this->url = $uri->toString(); } $msg = JText::sprintf('Server Error: %s url: %s', $result->body->error, JHtml::_('link', $this->url, $result->code, array('target' => '_blank'))); // TODO JText::_() throw new RuntimeException($msg); } return $result; }
/** * Test the toString method. * * @return void * * @since 11.1 * @covers JUri::toString */ public function testToString() { $this->object->parse('http://*****:*****@www.example.com:80/path/file.html?var=value#fragment'); $this->assertThat($this->object->toString(), $this->equalTo('http://*****:*****@www.example.com:80/path/file.html?var=value#fragment')); $this->object->setQuery('somevar=somevalue'); $this->object->setVar('somevar2', 'somevalue2'); $this->object->setScheme('ftp'); $this->object->setUser('root'); $this->object->setPass('secret'); $this->object->setHost('www.example.org'); $this->object->setPort('8888'); $this->object->setFragment('someFragment'); $this->object->setPath('/this/is/a/path/to/a/file'); $this->assertThat($this->object->toString(), $this->equalTo('ftp://*****:*****@www.example.org:8888/this/is/a/path/to/a/file?somevar=somevalue&somevar2=somevalue2#someFragment')); }
/** * A method to do Google translate. * * @param string $text String to translate. * @param string $SourceLan Translate from this language, eg: 'zh-tw'. Empty will auto detect. * @param string $ResultLan Translate to this language, eg: 'en'. Empty will auto detect. * * @return string|bool Translated text. */ public static function gTranslate($text, $SourceLan, $ResultLan) { $url = new \JUri(); // For Google APIv2 $url->setHost('https://www.googleapis.com/'); $url->setPath('language/translate/v2'); $query['key'] = self::APT_KEY; $query['q'] = urlencode($text); $query['source'] = $SourceLan; $query['target'] = $ResultLan; if (!$text) { return false; } $url->setQuery($query); $url->toString(); $response = CurlHelper::get((string) $url); if (empty($response->body)) { return ''; } $json = new \JRegistry(); $json->loadString($response->body, 'json'); $r = $json->get('data.translations'); return $r[0]->translatedText; }
/** * Send a command to the server and validate an expected response. * * @param string Command to send to the server. * @param mixed Valid response code or array of response codes. * * @return boolean True on success. * * @since 11.1 * @throws JException */ protected function _sendRequest($connection, $method, JUri $uri, $data = null, $headers = null) { // Make sure the connection is a valid resource. if (is_resource($connection)) { // Make sure the connection has not timed out. $meta = stream_get_meta_data($connection); if ($meta['timed_out']) { throw new JException('Server connection timed out.', 0, E_WARNING); } } else { throw new JException('Not connected to server.', 0, E_WARNING); } // Get the request path from the URI object. $path = $uri->toString(array('path', 'query')); // Build the request payload. $request = array(); $request[] = strtoupper($method) . ' ' . (empty($path) ? '/' : $path) . ' HTTP/1.0'; $request[] = 'Host: ' . $uri->getHost(); $request[] = 'User-Agent: JHttp | Joomla/2.0'; // If there are custom headers to send add them to the request payload. if (is_array($headers)) { foreach ($headers as $k => $v) { $request[] = $k . ': ' . $v; } } // If we have data to send add it to the request payload. if (!empty($data)) { // If the data is an array, build the request query string. if (is_array($data)) { $data = http_build_query($data); } $request[] = 'Content-Type: application/x-www-form-urlencoded; charset=utf-8'; $request[] = 'Content-Length: ' . strlen($data); $request[] = null; $request[] = $data; } // Send the request to the server. fwrite($connection, implode("\r\n", $request) . "\r\n\r\n"); // Get the response data from the server. $this->_response = null; while (!feof($connection)) { $this->_response .= fgets($connection, 4096); } return true; }
/** * Get the referrer page. * * If there's no referrer or it's external, Kunena will return default page. * Also referrers back to tasks are removed. * * @param string $default Default page to return into. * @param string $anchor Anchor (location in the page). * * @return string */ public static function getReferrer($default = null, $anchor = null) { $app = JFactory::getApplication(); $referrer = $app->input->server->getString('HTTP_REFERER'); if ($referrer) { $uri = new JUri($referrer); // Make sure we do not return into a task -- or if task is SEF encoded, make sure it fails. $uri->delVar('task'); $uri->delVar(JSession::getFormToken()); // Check that referrer was from the same domain and came from the Joomla frontend or backend. $base = $uri->toString(array('scheme', 'host', 'port', 'path')); $host = $uri->toString(array('scheme', 'host', 'port')); // Referrer should always have host set and it should come from the same base address. if (empty($host) || stripos($base, JUri::base()) !== 0) { $uri = null; } } if (!isset($uri)) { if ($default == null) { $default = $app->isSite() ? 'index.php?option=com_kunena' : 'administrator/index.php?option=com_kunena'; } $default = self::_($default); $uri = new JUri($default); } if ($anchor) { $uri->setFragment($anchor); } return $uri->toString(array('path', 'query', 'fragment')); }
function onAfterInitialise() { /** @var JSite $app */ $app = JFactory::getApplication(); if ($app->isAdmin()) { // don't use MobileJoomla in backend return; } $is_joomla15 = $this->isJoomla15(); //load MobileJoomla class require_once JPATH_ADMINISTRATOR . '/components/com_mobilejoomla/classes/mobilejoomla.php'; //load config $MobileJoomla_Settings =& MobileJoomla::getConfig(); $MobileJoomla_Device =& MobileJoomla::getDevice(); // check for legacy redirect if (@$_GET['option'] == 'com_mobilejoomla' && @$_GET['task'] == 'setmarkup' && isset($_GET['markup']) && isset($_GET['return'])) { $desktop_uri = new JUri($MobileJoomla_Settings['desktop_url']); $uri = new JUri(base64_decode($_GET['return'])); if (!$uri->getScheme()) { $uri->setScheme('http'); } $uri->setHost($desktop_uri->getHost()); $uri->setPort($desktop_uri->getPort()); $app->redirect($uri->toString()); } JPluginHelper::importPlugin('mobile'); $cached_data = $app->getUserState('mobilejoomla.cache'); if ($cached_data !== null) { $cached_data = @gzinflate(@base64_decode($cached_data)); if ($cached_data !== false) { $cached_data = @unserialize($cached_data); } } if (is_array($cached_data)) { $MobileJoomla_Device = $cached_data['device']; } else { $app->triggerEvent('onDeviceDetection', array(&$MobileJoomla_Settings, &$MobileJoomla_Device)); $gzlevel = 5; $cached_data = array('device' => $MobileJoomla_Device); $cached_data = base64_encode(gzdeflate(serialize($cached_data), $gzlevel)); $app->setUserState('mobilejoomla.cache', $cached_data); } $MobileJoomla_Device['markup'] = self::CheckMarkup($MobileJoomla_Device['markup']); $MobileJoomla_Device['real_markup'] = $MobileJoomla_Device['markup']; $app->triggerEvent('onAfterDeviceDetection', array(&$MobileJoomla_Settings, &$MobileJoomla_Device)); $MobileJoomla_Device['markup'] = self::CheckMarkup($MobileJoomla_Device['markup']); $markup = $MobileJoomla_Device['markup']; $MobileJoomla_Device['default_markup'] = $markup; //get user choice $user_markup = $this->getUserMarkup(); if ($user_markup !== false) { $markup = $user_markup; } // template preview $getTemplate = isset($_GET['template']) ? $_GET['template'] : null; if (version_compare(JVERSION, '1.7', '>=')) { if ($getTemplate === null && isset($_GET['templateStyle']) && is_int($_GET['templateStyle'])) { $db = JFactory::getDBO(); $query = 'SELECT template FROM #__template_styles WHERE id = ' . intval($_GET['templateStyle']) . ' AND client_id = 0'; $db->setQuery($query); $getTemplate = $db->loadResult(); } } elseif (version_compare(JVERSION, '1.6', '>=')) { if (is_int($getTemplate)) { $db = JFactory::getDBO(); $query = 'SELECT template FROM #__template_styles WHERE id = ' . intval($getTemplate) . ' AND client_id = 0'; $db->setQuery($query); $getTemplate = $db->loadResult(); } } if ($getTemplate) { switch ($getTemplate) { case $MobileJoomla_Settings['xhtml.template']: $markup = 'xhtml'; break; case $MobileJoomla_Settings['iphone.template']: $markup = 'iphone'; break; case $MobileJoomla_Settings['wml.template']: $markup = 'wml'; break; case $MobileJoomla_Settings['chtml.template']: $markup = 'chtml'; break; } } $MobileJoomla_Device['markup'] = $markup; if ($MobileJoomla_Device['screenwidth'] == 0 || $MobileJoomla_Device['screenheight'] == 0) { switch ($markup) { case 'wml': $MobileJoomla_Device['screenwidth'] = 64; $MobileJoomla_Device['screenheight'] = 96; break; case 'chtml': $MobileJoomla_Device['screenwidth'] = 120; $MobileJoomla_Device['screenheight'] = 128; break; case 'xhtml': $MobileJoomla_Device['screenwidth'] = 320; $MobileJoomla_Device['screenheight'] = 480; break; case 'iphone': $MobileJoomla_Device['screenwidth'] = 320; $MobileJoomla_Device['screenheight'] = 480; break; } } if ($MobileJoomla_Device['imageformats'] === null) { switch ($markup) { case 'wml': $MobileJoomla_Device['imageformats'] = array('wbmp'); break; case 'chtml': $MobileJoomla_Device['imageformats'] = array('gif'); break; case 'xhtml': case 'iphone': $MobileJoomla_Device['imageformats'] = array('png', 'gif', 'jpg'); break; } } if (count($MobileJoomla_Device['imageformats']) == 0) { $MobileJoomla_Settings['wml.img'] = 1; $MobileJoomla_Settings['chtml.img'] = 1; $MobileJoomla_Settings['xhtml.img'] = 1; $MobileJoomla_Settings['iphone.img'] = 1; } $app->triggerEvent('onBeforeMobileMarkupInit', array(&$MobileJoomla_Settings, &$MobileJoomla_Device)); $MobileJoomla_Device['markup'] = self::CheckMarkup($MobileJoomla_Device['markup']); $this->updateUserMarkup(); $app->triggerEvent('onMobileMarkupInit', array(&$MobileJoomla_Settings, &$MobileJoomla_Device)); $markup = $MobileJoomla_Device['markup']; if (empty($markup)) { $MobileJoomla_Device['markup'] = false; return; } $MobileJoomla = MobileJoomla::getInstance($markup); // set headers here to be compatible with System-Cache $MobileJoomla->setHeader(); if ($MobileJoomla_Settings['mobile_sitename']) { $this->setConfig('sitename', $MobileJoomla_Settings['mobile_sitename']); } if (!$is_joomla15) { if (!$MobileJoomla_Settings['caching']) { $this->setConfig('caching', 0); } $cachekey = MobileJoomla::getCacheKey(); $registeredurlparams = isset($app->registeredurlparams) ? $app->registeredurlparams : null; if (empty($registeredurlparams)) { $registeredurlparams = new stdClass(); } $this->setRequestVar('mjcachekey', $cachekey); $registeredurlparams->mjcachekey = 'CMD'; $this->setRequestVar('mjurlkey', JRequest::getURI()); $registeredurlparams->mjurlkey = 'STRING'; $app->registeredurlparams = $registeredurlparams; //fix System-Cache plugin in J!3.0 if (JPluginHelper::isEnabled('system', 'cache') && version_compare(JVERSION, '3.0.0', '>=')) { $dispatcher = JEventDispatcher::getInstance(); $refObj = new ReflectionObject($dispatcher); $refProp = $refObj->getProperty('_observers'); $refProp->setAccessible(true); $observers = $refProp->getValue($dispatcher); foreach ($observers as $index => $object) { if (is_a($object, 'plgSystemCache')) { $object->_cache_key = '~' . $cachekey . '~' . $object->_cache_key; } } } } else { if ($MobileJoomla_Settings['caching']) { /** @var JRegistry $config */ $config = JFactory::getConfig(); $handler = $config->getValue('config.cache_handler', 'file'); $handler .= '_mj'; $config->setValue('config.cache_handler', $handler); $class = 'JCacheStorage' . ucfirst($handler); $path = JPATH_ADMINISTRATOR . '/components/com_mobilejoomla/override/cachestorage/' . $handler . '.php'; jimport('joomla.cache.storage'); JLoader::register($class, $path); } else { $this->setConfig('caching', 0); //disable System-Cache plugin $dispatcher = JDispatcher::getInstance(); foreach ($dispatcher->_observers as $index => $object) { if (is_a($object, 'plgSystemCache')) { $object->_cache = new _CacheStub(); unset($dispatcher->_observers[$index]); break; } } } } if (@$_SERVER['REQUEST_METHOD'] != 'POST') { $router = $app->getRouter(); $router->attachBuildRule(array($this, 'buildRule')); } if (!defined('SHMOBILE_MOBILE_TEMPLATE_SWITCHED')) { define('SHMOBILE_MOBILE_TEMPLATE_SWITCHED', 1); } }
/** * Substitutes the [RENEWALURL:couponcode] tag in messages * * @param string $text The message text * @param string $renewalURL The base renewal URL (without a coupon code) * * @return string The text with the tag replaced with the proper URLs */ public static function substituteRenewalURLWithCoupon($text, $renewalURL) { // Find where the tag starts $nextPos = 0; $tagStartText = '[RENEWALURL:'; if (!class_exists('JUri', true)) { JLoader::import('joomla.environment.uri'); JLoader::import('joomla.uri.uri'); } $uri = new JUri($renewalURL); do { $pos = strpos($text, $tagStartText, $nextPos); if ($pos === false) { // Not found? No change. continue; } // Get the start position of the coupon name $couponStartPos = $pos + strlen($tagStartText); // Get the end position of the tag $endPos = strpos($text, ']', $couponStartPos); // If no end position is found, ignore the tag if ($endPos == $couponStartPos) { $nextPos = $couponStartPos + 1; continue; } // Get the coupon code $couponCode = substr($text, $couponStartPos, $endPos - $couponStartPos); // Create the URL $uri->setVar('coupon', $couponCode); $toReplace = substr($text, $pos, $endPos - $pos + 1); $text = str_replace($toReplace, $uri->toString(), $text); } while ($pos !== false); return $text; }
public function step() { // Check permissions $this->_checkPermissions(); // Set the profile $this->_setProfile(); // Get the backup ID $backupId = $this->input->get('backupid', null, 'raw', 2); if (empty($backupId)) { $backupId = null; } $kettenrad = AECoreKettenrad::load(AKEEBA_BACKUP_ORIGIN, $backupId); $kettenrad->setBackupId($backupId); $kettenrad->tick(); $array = $kettenrad->getStatusArray(); $kettenrad->resetWarnings(); // So as not to have duplicate warnings reports AECoreKettenrad::save(AKEEBA_BACKUP_ORIGIN, $backupId); if ($array['Error'] != '') { @ob_end_clean(); echo '500 ERROR -- ' . $array['Error']; flush(); JFactory::getApplication()->close(); } elseif ($array['HasRun'] == 1) { // All done AEFactory::nuke(); AEUtilTempvars::reset(); @ob_end_clean(); echo '200 OK'; flush(); JFactory::getApplication()->close(); } else { $noredirect = $this->input->get('noredirect', 0, 'int'); if ($noredirect != 0) { @ob_end_clean(); echo "301 More work required"; flush(); JFactory::getApplication()->close(); } else { $curUri = JUri::getInstance(); $ssl = $curUri->isSSL() ? 1 : 0; $tempURL = JRoute::_('index.php?option=com_akeeba', false, $ssl); $uri = new JUri($tempURL); $uri->setVar('view', 'backup'); $uri->setVar('task', 'step'); $uri->setVar('key', $this->input->get('key', '', 'none', 2)); $uri->setVar('profile', $this->input->get('profile', 1, 'int')); if (!empty($backupId)) { $uri->setVar('backupid', $backupId); } // Maybe we have a multilingual site? $lg = F0FPlatform::getInstance()->getLanguage(); $languageTag = $lg->getTag(); $uri->setVar('lang', $languageTag); $redirectionUrl = $uri->toString(); $this->_customRedirect($redirectionUrl); } } }
/** * Renders a Form for an Edit view and returns the corresponding HTML * * @param Form &$form The form to render * @param DataModel $model The model providing our data * * @return string The HTML rendering of the form */ public function renderFormEdit(Form &$form, DataModel $model) { // Get the key for this model's table $key = $model->getKeyName(); $keyValue = $model->getId(); $html = ''; $validate = strtolower($form->getAttribute('validate')); if (in_array($validate, array('true', 'yes', '1', 'on'))) { \JHTML::_('behavior.formvalidation'); $class = ' form-validate'; $this->loadValidationScript($form); } else { $class = ''; } // Check form enctype. Use enctype="multipart/form-data" to upload binary files in your form. $template_form_enctype = $form->getAttribute('enctype'); if (!empty($template_form_enctype)) { $enctype = ' enctype="' . $form->getAttribute('enctype') . '" '; } else { $enctype = ''; } // Check form name. Use name="yourformname" to modify the name of your form. $formname = $form->getAttribute('name'); if (empty($formname)) { $formname = 'adminForm'; } // Check form ID. Use id="yourformname" to modify the id of your form. $formid = $form->getAttribute('id'); if (empty($formid)) { $formid = $formname; } // Check if we have a custom task $customTask = $form->getAttribute('customTask'); if (empty($customTask)) { $customTask = ''; } // Get the form action URL $platform = $this->container->platform; $actionUrl = $platform->isBackend() ? 'index.php' : \JUri::root() . 'index.php'; $itemid = $this->container->input->getCmd('Itemid', 0); if ($platform->isFrontend() && $itemid != 0) { $uri = new \JUri($actionUrl); if ($itemid) { $uri->setVar('Itemid', $itemid); } $actionUrl = \JRoute::_($uri->toString()); } $html .= '<form action="' . $actionUrl . '" method="post" name="' . $formname . '" id="' . $formid . '"' . $enctype . ' class="form-horizontal' . $class . '">' . "\n"; $html .= "\t" . '<input type="hidden" name="option" value="' . $this->container->componentName . '" />' . "\n"; $html .= "\t" . '<input type="hidden" name="view" value="' . $form->getView()->getName() . '" />' . "\n"; $html .= "\t" . '<input type="hidden" name="task" value="' . $customTask . '" />' . "\n"; $html .= "\t" . '<input type="hidden" name="' . $key . '" value="' . $keyValue . '" />' . "\n"; $html .= "\t" . '<input type="hidden" name="' . \JFactory::getSession()->getFormToken() . '" value="1" />' . "\n"; $html .= $this->renderFormRaw($form, $model, 'edit'); $html .= '</form>'; return $html; }
$db->setQuery($query); $menus = $db->loadObjectList(); foreach ($menus as $menu) { if (!$menu->link) { continue; } if (in_array($menu->type, array('alias', 'url'))) { continue; } // Fix URI bugs $uri = new JUri($menu->link); $uri->setVar('Itemid', $menu->id); if ($app->get('sef')) { $uri->setVar('layout', null); } $link = JRoute::_($uri->toString()); $host = str_replace('http://' . $_SERVER['HTTP_HOST'], '', JUri::root()); $link = str_replace($host, '', $link); $link = UriHelper::pathAddHost($link); // Set xml data $sitemap->addItem($link, '0.8', 'weekly', $date); $linkCache[] = $link; } // Build category map $query = $db->getQuery(true); $query->select("*")->from("#__categories")->where("id != 1")->where("published = 1")->where("access = 1")->where("extension = 'com_content'"); if ($locale) { $query->where($query->format('language IN (%q, %q)', $locale, '*')); } $db->setQuery($query); $cats = $db->loadObjectList();
/** * getHost. * * @return string */ public static function getHost() { $baseurl = JUri::root(); $uri = new JUri(); if ($uri->parse($baseurl)) { $host = $uri->toString(array('scheme', 'host', 'port')); return $host; } return null; }
/** * Give a relative path, return path with host. * * @param string $path A system path. * * @return string Path with host added. */ public static function pathAddHost($path) { if (!$path) { return ''; } // Build path $uri = new \JUri($path); if ($uri->getHost()) { return $path; } $uri->parse(\JUri::root()); $root_path = $uri->getPath(); if (strpos($path, $root_path) === 0) { $num = Utf8String::strlen($root_path); $path = Utf8String::substr($path, $num); } $uri->setPath($uri->getPath() . $path); $uri->setScheme('http'); $uri->setQuery(null); return $uri->toString(); }
protected function getInput() { JHtml::_('jquery.framework'); JHtml::_('script', 'system/html5fallback.js', false, true); $path = JUri::root() . 'plugins/system/ef4_jmframework/includes/assets/admin/formfields/jmplupload'; $document = JFactory::getDocument(); $document->addScript($path . '/js/plupload.full.min.js'); $browse_button = !empty($this->element['browse_button']) ? JText::_($this->element['browse_button']) : JText::_('PLG_SYSTEM_JMFRAMEWORK_PLUPLOAD_BROWSE'); $upload_button = !empty($this->element['upload_button']) ? JText::_($this->element['upload_button']) : JText::_('PLG_SYSTEM_JMFRAMEWORK_PLUPLOAD_UPLOAD'); $browse_button_id = $this->id . '_browse'; $upload_button_id = $this->id . '_upload'; $container_id = $this->id . '_container'; $filelist_id = $this->id . '_files'; $console_id = $this->id . '_console'; $flash_url = $path . '/js/Moxie.swf'; $silverlight_url = $path . '/js/Moxie.xap'; $extensions = !empty($this->element['extensions']) ? $this->element['extensions'] : 'json,svg,eot,woff,ttf,otf,zip,jpg,jpeg,png,css'; $uri = JUri::getInstance(); $myuri = new JUri($uri->toString()); $myuri->setVar('jmajax', 'plupload'); $myuri->setVar('jmtask', (string) $this->element['task']); $myuri->setVar('jmpluploadid', $this->id); $url = $myuri->toString(); //JURI::reset(); $js = ' jQuery(document).ready(function(){ var JMPLUpload_' . $this->id . ' = new plupload.Uploader({ runtimes : \'html5,flash,silverlight,html4\', browse_button : \'' . $browse_button_id . '\', container: \'' . $container_id . '\', url : \'' . $url . '\', flash_swf_url : \'' . $flash_url . '\', silverlight_xap_url : \'' . $silverlight_url . '\', filters : { max_file_size : \'10mb\', mime_types: [ {title : "Allowed files", extensions : "' . $extensions . '"} ] }, init: { PostInit: function() { document.getElementById(\'' . $filelist_id . '\').innerHTML = \'\'; document.getElementById(\'' . $upload_button_id . '\').onclick = function() { JMPLUpload_' . $this->id . '.start(); return false; }; }, FilesAdded: function(up, files) { plupload.each(files, function(file) { document.getElementById(\'' . $filelist_id . '\').innerHTML += \'<div id="\' + file.id + \'">\' + file.name + \' (\' + plupload.formatSize(file.size) + \') <b></b></div>\'; }); }, UploadProgress: function(up, file) { document.getElementById(file.id).getElementsByTagName(\'b\')[0].innerHTML = \'<span>\' + file.percent + "%</span>"; }, Error: function(up, err) { document.getElementById(\'' . $console_id . '\').innerHTML += "\\nError #" + err.code + ": " + err.message; }, UploadComplete: function(up, file, undef) { jQuery(document).trigger("jmplupload_' . $this->id . '", [up, file, undef]); } } }); JMPLUpload_' . $this->id . '.init(); }); '; $document->addScriptDeclaration($js); $html = ' <div id="' . $container_id . '"> <span id="' . $browse_button_id . '" class="button btn">' . $browse_button . '</span> <span id="' . $upload_button_id . '" class="button btn">' . $upload_button . '</span> </div> <div> <p id="' . $console_id . '"></p> <p id="' . $filelist_id . '">Your browser doesn\'t have Flash, Silverlight or HTML5 support.</p> </div> '; return $html; }
/** * The update check and notification email code is triggered after the page has fully rendered. * * @return void * * @since 3.5 */ public function onAfterRender() { // Get the timeout for Joomla! updates, as configured in com_installer's component parameters JLoader::import('joomla.application.component.helper'); $component = JComponentHelper::getComponent('com_installer'); /** @var \Joomla\Registry\Registry $params */ $params = $component->params; $cache_timeout = (int) $params->get('cachetimeout', 6); $cache_timeout = 3600 * $cache_timeout; // Do we need to run? Compare the last run timestamp stored in the plugin's options with the current // timestamp. If the difference is greater than the cache timeout we shall not execute again. $now = time(); $last = (int) $this->params->get('lastrun', 0); if (!defined('PLG_SYSTEM_UPDATENOTIFICATION_DEBUG') && abs($now - $last) < $cache_timeout) { return; } // Update last run status // If I have the time of the last run, I can update, otherwise insert $this->params->set('lastrun', $now); $db = JFactory::getDbo(); $query = $db->getQuery(true)->update($db->qn('#__extensions'))->set($db->qn('params') . ' = ' . $db->q($this->params->toString('JSON')))->where($db->qn('type') . ' = ' . $db->q('plugin'))->where($db->qn('folder') . ' = ' . $db->q('system'))->where($db->qn('element') . ' = ' . $db->q('updatenotification')); try { // Lock the tables to prevent multiple plugin executions causing a race condition $db->lockTable('#__extensions'); } catch (Exception $e) { // If we can't lock the tables it's too risky to continue execution return; } try { // Update the plugin parameters $result = $db->setQuery($query)->execute(); $this->clearCacheGroups(array('com_plugins'), array(0, 1)); } catch (Exception $exc) { // If we failed to execite $db->unlockTables(); $result = false; } try { // Unlock the tables after writing $db->unlockTables(); } catch (Exception $e) { // If we can't lock the tables assume we have somehow failed $result = false; } // Abort on failure if (!$result) { return; } // This is the extension ID for Joomla! itself $eid = 700; // Get any available updates $updater = JUpdater::getInstance(); $results = $updater->findUpdates(array($eid), $cache_timeout); // If there are no updates our job is done. We need BOTH this check AND the one below. if (!$results) { return; } // Unfortunately Joomla! MVC doesn't allow us to autoload classes JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_installer/models', 'InstallerModel'); // Get the update model and retrieve the Joomla! core updates $model = JModelLegacy::getInstance('Update', 'InstallerModel'); $model->setState('filter.extension_id', $eid); $updates = $model->getItems(); // If there are no updates we don't have to notify anyone about anything. This is NOT a duplicate check. if (empty($updates)) { return; } // Get the available update $update = array_pop($updates); // Check the available version. If it's the same as the installed version we have no updates to notify about. if (version_compare($update->version, JVERSION, 'eq')) { return; } // If we're here, we have updates. First, get a link to the Joomla! Update component. $baseURL = JUri::base(); $baseURL = rtrim($baseURL, '/'); $baseURL .= substr($baseURL, -13) != 'administrator' ? '/administrator/' : '/'; $baseURL .= 'index.php?option=com_joomlaupdate'; $uri = new JUri($baseURL); /** * Some third party security solutions require a secret query parameter to allow log in to the administrator * backend of the site. The link generated above will be invalid and could probably block the user out of their * site, confusing them (they can't understand the third party security solution is not part of Joomla! proper). * So, we're calling the onBuildAdministratorLoginURL system plugin event to let these third party solutions * add any necessary secret query parameters to the URL. The plugins are supposed to have a method with the * signature: * * public function onBuildAdministratorLoginURL(JUri &$uri); * * The plugins should modify the $uri object directly and return null. */ JEventDispatcher::getInstance()->trigger('onBuildAdministratorLoginURL', array(&$uri)); // Let's find out the email addresses to notify $superUsers = array(); $specificEmail = $this->params->get('email', ''); if (!empty($specificEmail)) { $superUsers = $this->getSuperUsers($specificEmail); } if (empty($superUsers)) { $superUsers = $this->getSuperUsers(); } if (empty($superUsers)) { return; } /* Load the appropriate language. We try to load English (UK), the current user's language and the forced * language preference, in this order. This ensures that we'll never end up with untranslated strings in the * update email which would make Joomla! seem bad. So, please, if you don't fully understand what the * following code does DO NOT TOUCH IT. It makes the difference between a hobbyist CMS and a professional * solution! */ $jLanguage = JFactory::getLanguage(); $jLanguage->load('plg_system_updatenotification', JPATH_ADMINISTRATOR, 'en-GB', true, true); $jLanguage->load('plg_system_updatenotification', JPATH_ADMINISTRATOR, null, true, false); // Then try loading the preferred (forced) language $forcedLanguage = $this->params->get('language_override', ''); if (!empty($forcedLanguage)) { $jLanguage->load('plg_system_updatenotification', JPATH_ADMINISTRATOR, $forcedLanguage, true, false); } // Set up the email subject and body $email_subject = JText::_('PLG_SYSTEM_UPDATENOTIFICATION_EMAIL_SUBJECT'); $email_body = JText::_('PLG_SYSTEM_UPDATENOTIFICATION_EMAIL_BODY'); // Replace merge codes with their values $newVersion = $update->version; $jVersion = new JVersion(); $currentVersion = $jVersion->getShortVersion(); $jConfig = JFactory::getConfig(); $sitename = $jConfig->get('sitename'); $mailFrom = $jConfig->get('mailfrom'); $fromName = $jConfig->get('fromname'); $substitutions = array('[NEWVERSION]' => $newVersion, '[CURVERSION]' => $currentVersion, '[SITENAME]' => $sitename, '[URL]' => JUri::base(), '[LINK]' => $uri->toString(), '\\n' => "\n"); foreach ($substitutions as $k => $v) { $email_subject = str_replace($k, $v, $email_subject); $email_body = str_replace($k, $v, $email_body); } // Send the emails to the Super Users foreach ($superUsers as $superUser) { $mailer = JFactory::getMailer(); $mailer->setSender(array($mailFrom, $fromName)); $mailer->addRecipient($superUser->email); $mailer->setSubject($email_subject); $mailer->setBody($email_body); $mailer->Send(); } }
/** * Tests the processParseRules() method * * @return void * * @since 3.4 */ public function testProcessParseRules() { $uri = new JUri('index.php?start=42'); $object = new JRouterSite(array(), $this->getMockCmsApp(), TestMockMenu::create($this)); $object->setMode(JROUTER_MODE_SEF); $processParseRulesMethod = new ReflectionMethod('JRouterSite', 'processParseRules'); $processParseRulesMethod->setAccessible(true); $vars = $processParseRulesMethod->invokeArgs($object, array(&$uri)); $this->assertEquals('index.php', $uri->toString()); $this->assertEquals(array('limitstart' => '42'), $vars); }
/** * Renders a F0FForm for an Edit view and returns the corresponding HTML * * @param F0FForm &$form The form to render * @param F0FModel $model The model providing our data * @param F0FInput $input The input object * * @return string The HTML rendering of the form */ protected function renderFormEdit(F0FForm &$form, F0FModel $model, F0FInput $input) { // Get the key for this model's table $key = $model->getTable()->getKeyName(); $keyValue = $model->getId(); JHTML::_('behavior.tooltip'); $html = ''; $validate = strtolower($form->getAttribute('validate')); $class = ''; if (in_array($validate, array('true', 'yes', '1', 'on'))) { JHtml::_('behavior.formvalidation'); $class = 'form-validate '; $this->loadValidationScript($form); } // Check form enctype. Use enctype="multipart/form-data" to upload binary files in your form. $template_form_enctype = $form->getAttribute('enctype'); if (!empty($template_form_enctype)) { $enctype = ' enctype="' . $form->getAttribute('enctype') . '" '; } else { $enctype = ''; } // Check form name. Use name="yourformname" to modify the name of your form. $formname = $form->getAttribute('name'); if (empty($formname)) { $formname = 'adminForm'; } // Check form ID. Use id="yourformname" to modify the id of your form. $formid = $form->getAttribute('name'); if (empty($formid)) { $formid = 'adminForm'; } // Check if we have a custom task $customTask = $form->getAttribute('customTask'); if (empty($customTask)) { $customTask = ''; } // Get the form action URL $actionUrl = F0FPlatform::getInstance()->isBackend() ? 'index.php' : JUri::root() . 'index.php'; if (F0FPlatform::getInstance()->isFrontend() && $input->getCmd('Itemid', 0) != 0) { $itemid = $input->getCmd('Itemid', 0); $uri = new JUri($actionUrl); if ($itemid) { $uri->setVar('Itemid', $itemid); } $actionUrl = JRoute::_($uri->toString()); } $html .= '<form action="' . $actionUrl . '" method="post" name="' . $formname . '" id="' . $formid . '"' . $enctype . ' class="' . $class . '">' . PHP_EOL; $html .= "\t" . '<input type="hidden" name="option" value="' . $input->getCmd('option') . '" />' . PHP_EOL; $html .= "\t" . '<input type="hidden" name="view" value="' . $input->getCmd('view', 'edit') . '" />' . PHP_EOL; $html .= "\t" . '<input type="hidden" name="task" value="' . $customTask . '" />' . PHP_EOL; $html .= "\t" . '<input type="hidden" name="' . $key . '" value="' . $keyValue . '" />' . PHP_EOL; $html .= "\t" . '<input type="hidden" name="' . JFactory::getSession()->getFormToken() . '" value="1" />' . PHP_EOL; $html .= $this->renderFormRaw($form, $model, $input, 'edit'); $html .= '</form>'; return $html; }
/** * @return string */ protected function _getBaseUrl() { if (0) { // experimental $root = JUri::root(); $juri = new JUri($root); return '//' . $juri->toString(array('host', 'port', 'path')); } return JUri::root(); }
/** * Validates a Yubikey OTP against the Yubikey servers * * @param string $otp The OTP generated by your Yubikey * * @return boolean True if it's a valid OTP * * @since 3.2 */ public function validateYubikeyOtp($otp) { $server_queue = array('api.yubico.com', 'api2.yubico.com', 'api3.yubico.com', 'api4.yubico.com', 'api5.yubico.com'); shuffle($server_queue); $gotResponse = false; $check = false; $http = JHttpFactory::getHttp(); $token = JSession::getFormToken(); $nonce = md5($token . uniqid(rand())); while (!$gotResponse && !empty($server_queue)) { $server = array_shift($server_queue); $uri = new JUri('https://' . $server . '/wsapi/2.0/verify'); // I don't see where this ID is used? $uri->setVar('id', 1); // The OTP we read from the user $uri->setVar('otp', $otp); // This prevents a REPLAYED_OTP status of the token doesn't change // after a user submits an invalid OTP $uri->setVar('nonce', $nonce); // Minimum service level required: 50% (at least 50% of the YubiCloud // servers must reply positively for the OTP to validate) $uri->setVar('sl', 50); // Timeou waiting for YubiCloud servers to reply: 5 seconds. $uri->setVar('timeout', 5); try { $response = $http->get($uri->toString(), null, 6); if (!empty($response)) { $gotResponse = true; } else { continue; } } catch (Exception $exc) { // No response, continue with the next server continue; } } // No server replied; we can't validate this OTP if (!$gotResponse) { return false; } // Parse response $lines = explode("\n", $response->body); $data = array(); foreach ($lines as $line) { $line = trim($line); $parts = explode('=', $line, 2); if (count($parts) < 2) { continue; } $data[$parts[0]] = $parts[1]; } // Validate the response - We need an OK message reply if ($data['status'] != 'OK') { return false; } // Validate the response - We need a confidence level over 50% if ($data['sl'] < 50) { return false; } // Validate the response - The OTP must match if ($data['otp'] != $otp) { return false; } // Validate the response - The token must match if ($data['nonce'] != $nonce) { return false; } return true; }
/** * Get session start time */ protected function _testSessionInit() { $uri = new JUri(JUri::root()); if (isset($_SERVER['PHP_AUTH_PW']) && $_SERVER['PHP_AUTH_PW']) { $uri->setPass($_SERVER['PHP_AUTH_PW']); } if (isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER']) { $uri->setUser($_SERVER['PHP_AUTH_USER']); } $requestUrl = $uri->toString() . 'media/zoo/applications/jbuniversal/tools/test-session.php'; $values = array(); for ($j = 0; $j < 10; $j++) { $values[] = (double) $this->app->jbhttp->request($requestUrl . '?nocache=' . mt_rand()); } return array_sum($values) / doubleval(count($values)); }