public static function getCategoriesPerLanguage($config = array('filter.published' => array(0, 1), 'filter.languages' => array()), $index = null) { $hash = md5(serialize($config)); if (!isset(self::$_categoriesDataPerLanguage[$hash])) { $config = (array)$config; $db = JFactory::getDbo(); $query = "SELECT c.*, g.title AS groupname, exfg.name as extra_fields_group FROM #__k2_categories as c LEFT JOIN #__viewlevels AS g ON g.id = c.access"." LEFT JOIN #__k2_extra_fields_groups AS exfg ON exfg.id = c.extraFieldsGroup WHERE c.id>0"; if (!empty($config['filter.published'])) { $query .= ' and c.published in ('.ShlDbHelper::arrayToIntvalList($config['filter.published']).')'; } if (!empty($config['filter.languages'])) { $query .= ' and c.language in ('.ShlDbHelper::arrayToQuotedList($config['filter.languages']).')'; } $db->setQuery($query); $items = $db->loadObjectList($index); foreach ($items as &$item) { $item->title = $item->name; $item->parent_id = $item->parent; } self::$_categoriesDataPerLanguage[$hash] = $items; } return self::$_categoriesDataPerLanguage[$hash]; }
public function getUrlsCount($which = 'auto') { switch (strtolower($which)) { // we want to read all automatic urls (include duplicates) case 'auto': $numberOfUrls = ShlDbHelper::count($this->_getTableName(), '*', array('dateadd' => '0000-00-00')); break; // we want to read urls as per current selection input fields // ie : component, language, custom, ... // we want to read urls as per current selection input fields // ie : component, language, custom, ... case 'selected': $numberOfUrls = $this->getTotal(); break; case 'view404': case '404': $query = 'select count(*) from ' . $this->_db->quoteName($this->_getTableName()) . ' where ' . $this->_db->quoteName('dateadd') . '!=' . $this->_db->Quote('0000-00-00') . ' and ' . $this->_db->quoteName('newurl') . '=' . $this->_db->Quote(''); try { $this->_db->setQuery($query); $numberOfUrls = $this->_db->shlLoadResult(); } catch (Exception $e) { ShlSystem_Log::error('sh404sef', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, $e->getMessage()); $numberOfUrls = 0; } break; default: $numberOfUrls = 0; break; } return intval($numberOfUrls); }
function shFetchPostId($show, $option, $shLangName) { if (empty($show)) { return null; } try { $postId = ShlDbHelper::selectResult('#__myblog_permalinks', 'contentid', array('permalink' => $show)); } catch (Exception $e) { ShlSystem_Log::error('sh404sef', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, $e->getMessage()); } return isset($postId) ? $postId : ''; }
/** * Delete a list of aliases from their ids, * passed as params * * @param array of integer $ids the list of aliases id to delete * @return boolean true if success */ public function deleteByIds($ids = array()) { if (empty($ids)) { return false; } try { ShlDbHelper::deleteIn($this->_getTableName(), 'id', $ids, ShlDbHelper::INTEGER); } catch (Exception $e) { $this->setError('Internal database error # ' . $e->getMessage()); return false; } return true; }
/** * * Get details of the "Uncategorized" category for a given extension, * storing the result in a cache variable * * @param string $extension full name of extension, ie "com_content" */ public static function getSh404sefContentCat() { // if not already in cache if (is_null(self::$_sh404sefContentCat)) { try { // read details from database self::$_sh404sefContentCat = ShlDbHelper::selectObject('#__categories', '*', array('parent_id' => 1, 'extension' => 'com_content', 'path' => 'sh404sef-custom-content', 'level' => 1)); } catch (Exception $e) { self::$_sh404sefContentCat = null; } } return self::$_sh404sefContentCat; }
/** * Returns a list of items as objects * as selected in the db based on passed * options (ie $options = array( 'id' => 12);) * * Data is not cached! * * @param array $options an array of key/ value pairs representing select params * @param boolean if true, method will only count matching records * * @return array of objects */ public function getByAttr($options, $countOnly = false) { try { if ($countOnly) { $list = ShlDbHelper::count($this->_getTableName(), '*', $options); } else { $list = ShlDbHelper::selectObjectList($this->_getTableName(), '*', $options); } } catch (Exception $e) { $list = $countOnly ? 0 : array(); ShlSystem_Log::error('sh404sef', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, $e->getMessage()); } return $list; }
/** * Creates a record in the database, based * on data read from import file * * @param array $header an array of fields, as built from the header line * @param string $line raw record obtained from import file */ protected function _createRecord($header, $line) { // extract the record $line = $this->_lineToArray(trim($line)); // get table object to store record $model = ShlMvcModel_Base::getInstance('metas', 'Sh404sefModel'); // bind table to current record $record = array(); $record['newurl'] = $line[1]; $record['metatitle'] = $line[4]; $record['metadesc'] = $line[2]; $record['metakey'] = $line[3]; $record['metalang'] = $line[5]; $record['metarobots'] = $line[6]; // clean up records foreach ($record as $key => $value) { if ($value == ' ') { $record[$key] = ''; } } // find if there is already an url record for this non-sef url. If so // we want the imported record to overwrite the existing one. // while makinf sure we're doing that with the main url, not one of the duplicates $existingRecords = $model->getByAttr(array('newurl' => $record['newurl'])); if (!empty($existingRecords)) { $existingRecord = $existingRecords[0]; // getByAttr always returns an array // use the existing id, this will be enought to override existing record when saving $record['id'] = $existingRecord->id; // ensure consistency : delete the remaining records, though there is no reason // there can be more than one record with same SEF AND same SEF array_shift($existingRecords); if (!empty($existingRecords)) { ShlDbHelper::deleteIn('#__sh404sef_metas', 'id', $existingRecords, ShlDbHelper::INTEGER); } } else { $record['id'] = 0; } // save record : returns the record id, so failure is when 0 is returned $status = $model->save($record); if (!$status) { // rethrow a more appropriate error message throw new Sh404sefExceptionDefault(JText::sprintf('COM_SH404SEF_IMPORT_ERROR_INSERTING_INTO_DB', $line[0])); } }
/** * Fetch a non-sef url directly from database * * @param string $sefUrl the sefurl we are searching a non sef for * @param string $nonSefUrl will be set to non sef url found * @return integer code, either none found, or the url pair type: custom or automatic */ public function getNonSefUrlFromDatabase(&$sefUrl, &$nonSefUrl) { try { $result = ShlDbHelper::selectObject($this->_getTableName(), array('oldurl', 'newurl', 'dateadd'), array('oldurl' => $sefUrl), array(), $orderBy = array('rank')); } catch (Exception $e) { return sh404SEF_URLTYPE_NONE; } if (empty($result->newurl)) { // no match, that's a 404 for us return sh404SEF_URLTYPE_404; } // found it $nonSefUrl = $result->newurl; // also adjust sefurl, as the one we have found in db might have a different case from original $sefUrl = $result->oldurl; // return code: either custom or automatic url return $result->dateadd == '0000-00-00' ? sh404SEF_URLTYPE_AUTO : sh404SEF_URLTYPE_CUSTOM; }
public static function updateShurls() { $pageInfo =& Sh404sefFactory::getPageInfo(); $sefConfig =& Sh404sefFactory::getConfig(); $pageInfo->shURL = empty($pageInfo->shURL) ? '' : $pageInfo->shURL; if ($sefConfig->enablePageId && !$sefConfig->stopCreatingShurls) { try { jimport('joomla.utilities.string'); $nonSefUrl = JString::ltrim($pageInfo->currentNonSefUrl, '/'); $nonSefUrl = shSortURL($nonSefUrl); // make sure we have a language $nonSefUrl = shSetURLVar($nonSefUrl, 'lang', $pageInfo->currentLanguageShortTag); // remove tracking vars (Google Analytics) $nonSefUrl = Sh404sefHelperGeneral::stripTrackingVarsFromNonSef($nonSefUrl); // try to get the current shURL, if any $shURL = ShlDbHelper::selectResult('#__sh404sef_pageids', array('pageid'), array('newurl' => $nonSefUrl)); // if none, we may have to create one if (empty($shURL)) { $shURL = self::_createShurl($nonSefUrl); } // insert in head and header, if not empty if (!empty($shURL)) { $fullShURL = JString::ltrim($pageInfo->getDefaultFrontLiveSite(), '/') . '/' . $shURL; $document = JFactory::getDocument(); if ($sefConfig->insertShortlinkTag) { $document->addHeadLink($fullShURL, 'shortlink'); // also add header, especially for HEAD requests JResponse::setHeader('Link', '<' . $fullShURL . '>; rel=shortlink', true); } if ($sefConfig->insertRevCanTag) { $document->addHeadLink($fullShURL, 'canonical', 'rev', array('type' => 'text/html')); } if ($sefConfig->insertAltShorterTag) { $document->addHeadLink($fullShURL, 'alternate shorter'); } // store for reuse $pageInfo->shURL = $shURL; } } catch (Exception $e) { ShlSystem_Log::error('sh404sef', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, $e->getMessage()); } } }
public function getArticle($id) { // sanitize input $id = intval($id); if (empty($id)) { throw new Sh404sefExceptionDefault('Invalid article id passed to ' . __METHOD__ . ' in ' . __CLASS__, 500); } // already cached ? if (empty(self::$_articles[$id])) { // read details about the article $article = ShlDbHelper::selectObject('#__content', array('id', 'title', 'alias', 'catid', 'language'), array('id' => $id)); // if not found, that's bad if (empty($article)) { throw new Sh404sefExceptionDefault('Non existing article id (' . $id . ') passed to ' . __METHOD__ . ' in ' . __CLASS__, 500); } // store our cached record self::$_articles[$id][$article->language] = $article; } return self::$_articles[$id]; }
/** * Saves data from the quickStart pane on main dashboard */ public function saveqcontrol() { // Check for request forgeries. JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); try { // get current settings for sh404SEF $params = Sh404sefHelperGeneral::getComponentParams($forceRead = true); // set params from the form $params->set('Enabled', JRequest::getInt('Enabled', 0)); $params->set('canReadRemoteConfig', JRequest::getInt('canReadRemoteConfig', 0)); $params->set('shRewriteMode', JRequest::getInt('shRewriteMode', 1)); $params->set('shSecEnableSecurity', JRequest::getInt('shSecEnableSecurity', 1)); // convert to json and store into db $textParams = $params->toString(); ShlDbHelper::update('#__extensions', array('params' => $textParams), array('element' => 'com_sh404sef', 'type' => 'component')); JFactory::getApplication()->enqueueMessage(JText::_('COM_SH404SEF_ELEMENT_SAVED')); } catch (Exception $e) { JFactory::getApplication()->enqueueMessage(JText::_('COM_SH404SEF_ELEMENT_NOT_SAVED'), 'error'); } parent::display(); }
/** * Creates a record in the database, based * on data read from import file * * @param array $header an array of fields, as built from the header line * @param string $line raw record obtained from import file */ protected function _createRecord($header, $line) { // extract the record $line = $this->_lineToArray($line); // get table object to store record $model = ShlMvcModel_Base::getInstance('aliases', 'Sh404sefModel'); // bind table to current record $record = array(); $record['newurl'] = $line[3]; if ($record['newurl'] == '__ Homepage __') { $record['newurl'] = sh404SEF_HOMEPAGE_CODE; } $record['alias'] = $line[1]; $record['type'] = $line[4]; // find if there is already same alias record for this non-sef url. If so // we want the imported record to overwrite the existing one. $existingRecords = $model->getByAttr(array('newurl' => $record['newurl'], 'alias' => $record['alias'])); if (!empty($existingRecords)) { $existingRecord = $existingRecords[0]; // getByAttr always returns an array // use the existing id, this will be enought to override existing record when saving $record['id'] = $existingRecord->id; // ensure consistency : delete the remaining records, though there is no reason // there can be more than one record with same alias AND same SEF array_shift($existingRecords); if (!empty($existingRecords)) { ShlDbHelper::deleteIn('#__sh404sef_aliases', 'id', $existingRecords, ShlDbHelper::INTEGER); } } // save record : returns the record id, so failure is when 0 is returned $saveId = $model->save($record); if (empty($saveId)) { // rethrow a more appropriate error message throw new Sh404sefExceptionDefault(JText::sprintf('COM_SH404SEF_IMPORT_ERROR_INSERTING_INTO_DB', $line[0])); } }
/** * Make the url with id = $cid the main url * in case of duplicates. Also set the previous * main url as secondary, swapping their rank * * @param integer $cid */ public function makeMainUrl($cid) { // get this url record $newMain = $this->getById($cid); $error = $this->getError(); if (!empty($error)) { return; } // is this already the main url ? if ($newMain->rank == 0) { return; } // now get the current main url $options = array('rank' => 0, 'oldurl' => $newMain->oldurl); $previousMains = $this->getByAttr($options); try { // if we got it, do the swapping if (!empty($previousMains)) { foreach ($previousMains as $previousMain) { ShlDbHelper::update($this->_getTableName(), array('rank' => $newMain->rank), array('id' => $previousMain->id)); // another thing we have to do is attach any meta data to the new // main url, so that they keep showing. Meta data are attached to // a NON-sef url, which has the benefit of keeping the attachement // whenever sef url creations are modified and sef urls recreated // but require a bit more work in that case ShlDbHelper::update('#__sh404sef_metas', array('newurl' => $newMain->newurl), array('newurl' => $previousMain->newurl)); } } // finally make it the main url ShlDbHelper::update($this->_getTableName(), array('rank' => 0), array('id' => $newMain->id)); } catch (Exception $e) { $this->setError('Internal database error # ' . $e->getMessage()); } }
$title[] = $sh_LANG[$shLangIso]['_SH404SEF_IJOOMLA_MAG_VIEW_MAGAZINE']; } catch (Exception $e) { $dosef = false; ShlSystem_Log::error('sh404sef', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, $e->getMessage()); } } else { $dosef = false; } break; case 'show_edition': if ($sefConfig->shInsertIJoomlaMagName) { $title[] = $shIJoomlaMagName; } if (!empty($id)) { try { $result = ShlDbHelper::selectObject('#__magazine_categories', array('id', 'title'), array('id' => $id)); $shRef = empty($result) ? $sh_LANG[$shLangIso]['_SH404SEF_IJOOMLA_MAG_EDITION'] . $sefConfig->replacement . $id : ($sefConfig->shInsertIJoomlaMagIssueId ? $id . $sefConfig->replacement : ''); // if name, put ID only if requested $title[] = $shRef . (empty($result) ? '' : $result->title); shRemoveFromGETVarsList('id'); $title[] = $sh_LANG[$shLangIso]['_SH404SEF_IJOOMLA_MAG_SHOW_EDITION']; } catch (Exception $e) { $dosef = false; ShlSystem_Log::error('sh404sef', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, $e->getMessage()); } } else { $dosef = false; } break; case 'show_article': if ($sefConfig->shInsertIJoomlaMagName) {
/** * Creates a link to the shLib plugin page * @return string */ public static function getShLibPluginLink($xhtml = true) { try { $pluginId = ShlDbHelper::selectResult('#__extensions', array('extension_id'), array('type' => 'plugin', 'element' => 'shlib', 'folder' => 'system')); } catch (Exception $e) { ShlSystem_Log::error('sh404sef', __CLASS__ . '/' . __METHOD__ . '/' . __LINE__ . ': ' . $e->getMessage()); } $link = ''; $pluginId = (int) $pluginId; if (!empty($pluginId)) { $link = 'index.php?option=com_plugins&task=plugin.edit&extension_id=' . $pluginId; } if ($xhtml) { $link = htmlspecialchars($link); } return $link; }
} if (!empty($pagenum)) { $pattern = str_replace($sefConfig->pagerep, ' ', $sefConfig->pageTexts[$shPageInfo->currentLanguageTag]); $pageNumber = str_replace('%s', $pagenum, $pattern); } } else { if (!empty($showall)) { $pageNumber = titleToLocation(JText::_('All Pages')); } } } } // V 1.2.4.j 2007/04/11 : numerical ID, on some categories only if ($sefConfig->shInsertNumericalId && isset($sefConfig->shInsertNumericalIdCatList) && !empty($id) && $view == 'view') { try { $contentElement = ShlDbHelper::selectObject('#__content', array('id', 'catid', 'created'), array('id' => $id)); if (!empty($contentElement)) { // V 1.2.4.t $foundCat = array_search(@$contentElement->catid, $sefConfig->shInsertNumericalIdCatList); if ($foundCat !== null && $foundCat !== false || $sefConfig->shInsertNumericalIdCatList[0] == '') { // test both in case PHP < 4.2.0 $shTemp = explode(' ', $contentElement->created); $title[] = str_replace('-', '', $shTemp[0]) . $contentElement->id; } } } catch (Exception $e) { ShlSystem_Log::error('sh404sef', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, $e->getMessage()); } } // end of edition id insertion $title = array_reverse($title);
private function _buildPageId() { $shURL = ''; $nextId = $this->_getNextDBId($this->_db->getPrefix() . 'sh404sef_pageids'); if ($nextId !== false) { $nextId = base_convert(18 + $nextId, 10, 18); for ($c = 0; $c < strlen($nextId); ++$c) { $char = base_convert($nextId[$c], 18, 10); $shURL .= self::$_regular[$char]; } } // now check if this shurl is not an existing // SEF or alias. If so, use the alternate char set // to create a new shurl, and try again. // using alternate char set (instead of simply increasing nextId) // makes sure that next time we try to create a shurl (for next URL) // we won't try something we've already used, making the number of attempts // for each shurl creation grows each time there is a collision try { $attempts = 0; $maxAttempts = 8; // don't need to check for collisions with existing shurls // as we use the next insert id, and code that using a unique char set //however, if we need to modify the shurl because it collides with // an existing SEF url or an alias, we will do so using the alternate // character set, so the new shurl don't risk collision with a regular // shurl but it may then collide with another, previously modified shurl // and so we need to check for shurl collisions when this happens $doneShurl = true; // however, need to check for collisions with regular sef urls and aliases $doneSef = false; $doneAlias = false; // and for bad language $doneClean = false; // prepare user set bad language/exclusion list $sefConfig =& Sh404sefFactory::getConfig(); $sefConfig->shurlBlackList = JString::trim($sefConfig->shurlBlackList); if (empty($sefConfig->shurlBlackList)) { $blackList = array(); } else { if (strpos($sefConfig->shurlBlackList, '|') !== false) { $blackList = explode('|', $sefConfig->shurlBlackList); } else { $blackList = array($sefConfig->shurlBlackList); } } $doneBlackList = false; do { // clean word check if (!$doneClean) { if (in_array($shURL, self::$_badWords)) { // bad language $attempts++; // build a new shurl, by changing a character // with one from the alternate set $shURL = $this->_getModifiedShurl($shURL); // invalidate shurl and alias check flag, to check again with this new shurl $doneShurl = false; $doneAlias = false; $doneSef = false; $doneBlackList = false; } else { $doneClean = true; } } // user word black list if (!$doneBlackList) { if (in_array($shURL, $blackList)) { // bad language $attempts++; // build a new shurl, by changing a character // with one from the alternate set $shURL = $this->_getModifiedShurl($shURL); // invalidate shurl and alias check flag, to check again with this new shurl $doneShurl = false; $doneAlias = false; $doneSef = false; $doneClean = false; } else { $doneBlackList = true; } } // regular SEF url collision check if (!$doneSef) { $isSEF = (int) ShlDbHelper::count('#__sh404sef_urls', '*', $this->_db->quoteName('oldurl') . ' = ? and ' . $this->_db->quoteName('newurl') . ' <> ?', array($shURL, '')); if (!empty($isSEF)) { // there is already a SEF url like that $attempts++; // build a new shurl, by changing a character // with one from the alternate set $shURL = $this->_getModifiedShurl($shURL); // invalidate shurl and alias check flag, to check again with this new shurl $doneShurl = false; $doneAlias = false; $doneClean = false; $doneBlackList = false; } else { $doneSef = true; } } // previous shurl check if (!$doneShurl) { $isShurl = (int) ShlDbHelper::count('#__sh404sef_pageids', '*', array('pageid' => $shURL, 'type' => Sh404sefHelperGeneral::COM_SH404SEF_URLTYPE_PAGEID)); if (!empty($isShurl)) { // there is already a shurl like that $attempts++; // build a new shurl, by changing a character // with one from the alternate set $shURL = $this->_getModifiedShurl($shURL); // invalidate regular sef and alias check flag, to check again with this new shurl $doneSef = false; $doneAlias = false; $doneClean = false; $doneBlackList = false; } else { $doneShurl = true; } } // alias collision check if (!$doneAlias) { $isAlias = (int) ShlDbHelper::count('#__sh404sef_aliases', '*', array('alias' => $shURL, 'type' => Sh404sefHelperGeneral::COM_SH404SEF_URLTYPE_ALIAS)); if (!empty($isAlias)) { // there is already an alias like that $attempts++; // build a new shurl, by changing a character // with one from the alternate set $shURL = $this->_getModifiedShurl($shURL); // invalidate regular sef and shurl check flag, to check again with this new shurl $doneSef = false; $doneShurl = false; $doneClean = false; $doneBlackList = false; } else { $doneAlias = true; } } } while ((!$doneSef || !$doneAlias || !$doneShurl || !$doneClean || !$doneBlackList) && $attempts < $maxAttempts); } catch (Exception $e) { } return $shURL; }
/** Returns the array of texts used by the extension for creating URLs * in currently selected language (for JoomFish support) * * @param string Extension name * @return array Extension's texts */ function getExtTexts($option, $lang = '') { $database = ShlDbHelper::getDb(); static $extTexts; if ($option == '') { return false; } // Set the language if ($lang == '') { $lang = SEFTools::getLangLongCode(); } if (!isset($extTexts)) { $extTexts = array(); } if (!isset($extTexts[$option])) { $extTexts[$option] = array(); } if (!isset($extTexts[$option][$lang])) { $extTexts[$option][$lang] = array(); // If lang is different than current language, change it if ($lang != SEFTools::getLangLongCode()) { $language = JFactory::getLanguage(); $oldLang = $language->setLanguage($lang); $language->load(); } $query = "SELECT `id`, `name`, `value` FROM `#__sefexttexts` WHERE `extension` = '{$option}'"; $database->setQuery($query); $texts = $database->loadObjectList(); if (is_array($texts) && count($texts) > 0) { foreach (array_keys($texts) as $i) { $name = $texts[$i]->name; $value = $texts[$i]->value; $extTexts[$option][$lang][$name] = $value; } } // Set the language back to previously selected one if (isset($oldLang) && $oldLang != SEFTools::getLangLongCode()) { $language = JFactory::getLanguage(); $language->setLanguage($oldLang); $language->load(); } } return $extTexts[$option][$lang]; }
public static function getDBO() { if (!isset(self::$_dbo)) { self::$_dbo = ShlDbHelper::getDb(); } }
$title[] = $shCBName; } $title[] = $sh_LANG[$shLangIso]['_SH404SEF_CB_MANAGE_AVATAR']; shRemoveFromGETVarsList('task'); break; } break; case 'emailuser': if ($sefConfig->shInsertCBName) { $title[] = $shCBName; } $title[] = $sh_LANG[$shLangIso]['_SH404SEF_CB_EMAIL_USER']; // add user name if set to do so / user id is in $uid if ($sefConfig->shCBInsertUserName) { try { $result = ShlDbHelper::selectResult('#__users', array(($sefConfig->shCBUseUserPseudo ? 'user' : '') . 'name'), array('id' => $uid)); } catch (Exception $e) { ShlSystem_Log::error('sh404sef', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, $e->getMessage()); } $title[] = empty($result) ? $sh_LANG[$shLangIso]['_SH404SEF_CB_USER'] . $sefConfig->replacement . $uid : ($sefConfig->shCBInsertUserId ? $uid . $sefConfig->replacement . $result : $result); // if name, put ID only if requested shRemoveFromGETVarsList('uid'); } shRemoveFromGETVarsList('task'); break; case 'teamcredits': if ($sefConfig->shInsertCBName) { $title[] = $shCBName; } $title[] = $sh_LANG[$shLangIso]['_SH404SEF_CB_TEAM_CREDITS']; shRemoveFromGETVarsList('task');
/** * * @param string $url * @param array $title * @param string $task * @param int $limit * @param int $limitstart * @return sefurl */ public static function sefGetLocation($nonSefUrl, &$title, $task = null, $limit = null, $limitstart = null, $langParam = null, $showall = null, $suppressPagination = false) { try { $shPageInfo =& Sh404sefFactory::getPageInfo(); $sefConfig =& Sh404sefFactory::getConfig(); $lang = empty($langParam) ? $shPageInfo->currentLanguageTag : $langParam; // shumisha : try to avoid duplicate content on multilingual sites by always adding &lang=xx to url (stored in DB). // warning : must add &lang=xx only if it does not exists already if (!strpos($nonSefUrl, 'lang=')) { $shSepString = substr($nonSefUrl, -9) == 'index.php' ? '?' : '&'; $nonSefUrl .= $shSepString . 'lang=' . shGetIsoCodeFromName($lang); } // make sure url is consistent $nonSefUrl = str_replace('&', '&', $nonSefUrl); // detect multipage homepage $shMultiPageHomePageFlag = shIsHomepage($nonSefUrl); // get all the slugs ready for being urls bits $tempSefUrl = array(); foreach ($title as $titlestring) { $decodedTitletring = urldecode($titlestring); $tempSefUrl[] = titleToLocation($decodedTitletring); } // now build the URL $tempSefUrl = implode("/", $tempSefUrl); // remove duplicate / $tempSefUrl = ShlSystem_Strings::pr('/\\/{2,}/u', '/', $tempSefUrl); // and truncate to max length, according to param $tempSefUrl = JString::substr($tempSefUrl, 0, sh404SEF_MAX_SEF_URL_LENGTH); // trim to max length V 1.2.4.t // if URL is empty, and unless this is a paginated home page, or home page in non-default language, stop there if (empty($tempSefUrl)) { if ((!shIsMultilingual() || shIsMultilingual() && shIsDefaultlang($lang)) && !$sefConfig->addFile && !$shMultiPageHomePageFlag) { // return ''; } // if location is empty, and not multilingual site, or multilingual, but this is default language, then there is nothing to add to url } // we have a valid SEF url, built with the data ($title) sent // by plugin. Now we want to check if it's already in the db // and add it if not // first, we search the memory cache for the non-sef url // as it is faster than looking up the db $finalSefUrl = ''; $sefUrlType = Sh404sefHelperCache::getSefUrlFromCache($nonSefUrl, $finalSefUrl); // if non-sef was not found in cache - or found, but it was a 404 last time we saw it - // we should continue and try adding it if ($sefUrlType == sh404SEF_URLTYPE_NONE || $sefUrlType == sh404SEF_URLTYPE_404) { $finalSefUrl = false; // non-sef was not found in cache, let's look up the database if ($sefUrlType == sh404SEF_URLTYPE_NONE) { $finalSefUrl = ShlDbHelper::selectResult('#__sh404sef_urls', 'oldurl', array('newurl' => $nonSefUrl)); } // we found the sef url in database, we're done if (!empty($finalSefUrl)) { return $finalSefUrl; } // the non-sef url is not in memory cache, nor in database // that's a new one, we need to finalize its sef (add pagination and language information) // After finalizing it, we'll also check that sef is not in the db // as it can already be there, associated with another non-sef (ie: a duplicate) // Either way we'll add it in the db, but mark it as a duplicate if needed // add pagination information, unless we were instructed by extension plugin not to // find if we should separate pagination info from sef with a / or not if (!empty($tempSefUrl)) { $shSeparator = JString::substr($tempSefUrl, -1) == '/' ? '' : '/'; } else { $shSeparator = ''; } $finalSefUrl = $suppressPagination ? $tempSefUrl : shAddPaginationInfo($limit, $limitstart, $showall, 1, $nonSefUrl, $tempSefUrl, $shSeparator); // v 1.2.4.t // if home page, we don't record anything, just return "home page" if ($shMultiPageHomePageFlag && '/' . $finalSefUrl == $tempSefUrl && (!shIsMultilingual() || shIsMultilingual() && shIsDefaultLang($lang))) { // but this is default language // this is start page of multipage homepage, return home or forced home if (!empty($sefConfig->shForcedHomePage)) { return str_replace($shPageInfo->getDefaultFrontLiveSite() . '/', '', $sefConfig->shForcedHomePage); } else { return ''; } } // add language information // first, remove languages in non-sef, to see if we're on homepage // as handling is sligthly different for homepage $v1 = shCleanUpLang($nonSefUrl); $v2 = shCleanUpLang($shPageInfo->homeLink); if ($v1 == $v2 || $v1 == 'index.php') { // check if this is homepage if (shIsMultilingual() && !shIsDefaultLang($lang)) { // if homepage in not-default-language, then add language code regardless of user settings // as we otherwise would not be able to switch language on the frontpage $finalSefUrl = shGetIsoCodeFromName($lang) . '/'; } else { $finalSefUrl = ''; } } else { // not on homepage, insert lang code based on user setting $option = shGetURLVar($nonSefUrl, 'option', ''); if (shInsertIsoCodeInUrl($option, $lang)) { // insert language code based on param // pass URL lang info, as may not be current lang $finalSefUrl = shGetIsoCodeFromName($lang) . '/' . $finalSefUrl; // must be forced lang, not default } } // after adding pagination part of SEF, and adding language code // the new SEF url is now complete and we can try adding to it cache and db if ($finalSefUrl != '') { $dburl = null; $dbUrlId = null; $nonSefUrlType = sh404SEF_URLTYPE_NONE; // search the memory cache for this new sef if ($sefConfig->shUseURLCache) { $nonSefUrlType = Sh404sefHelperCache::getNonSefUrlFromCache($finalSefUrl, $dburl); } $newMaxRank = 0; // if the new SEF was not found in memory cache, or if it was found but // we're set to record duplicates, we search for it in the database if ($sefConfig->shRecordDuplicates || $nonSefUrlType == sh404SEF_URLTYPE_NONE) { $dbUrlList = ShlDbHelper::selectObjectList('#__sh404sef_urls', array('id', 'newurl', 'rank', 'dateadd'), array('oldurl' => $finalSefUrl), $aWhereData = array(), $orderBy = array('rank')); if (count($dbUrlList) > 0) { $dburl = $dbUrlList[0]->newurl; $dbUrlId = $dbUrlList[0]->id; if (empty($dburl)) { // V 1.2.4.t url was found in DB, but was a 404 $nonSefUrlType = sh404SEF_URLTYPE_404; } else { $newMaxRank = $dbUrlList[count($dbUrlList) - 1]->rank + 1; $nonSefUrlType = $dbUrlList[0]->dateadd == '0000-00-00' ? sh404SEF_URLTYPE_AUTO : sh404SEF_URLTYPE_CUSTOM; } } } if ($nonSefUrlType != sh404SEF_URLTYPE_NONE && $nonSefUrlType != sh404SEF_URLTYPE_404) { // we found the SEF, one or more times in the db, in records which do have a non-sef attached $isDuplicate = $dburl != $nonSefUrl; // This is a duplicate so we must indert it with incremented rank; if (is_null($dburl) || $isDuplicate && $sefConfig->shRecordDuplicates) { // shAddSefUrlToDBAndCache( $nonSefUrl, $finalSefUrl, ($isDuplicate ? $newMaxRank : 0), $nonSefUrlType); $dateAdd = $nonSefUrlType == sh404SEF_URLTYPE_AUTO ? '0000-00-00' : date("Y-m-d"); ShlDbHelper::insert('#__sh404sef_urls', array('oldurl' => $finalSefUrl, 'newurl' => $nonSefUrl, 'rank' => $isDuplicate ? $newMaxRank : 0, 'dateadd' => $dateAdd)); // store new sef/non-sef pair in memory cache Sh404sefHelperCache::addSefUrlToCache($nonSefUrl, $finalSefUrl, $nonSefUrlType); // create shURL : get a shURL model, and ask url creation $model = ShlMvcModel_Base::getInstance('pageids', 'Sh404sefModel'); $model->createPageId($finalSefUrl, $nonSefUrl); } } else { // we haven't found the non-sef/sef pair, but maybe there is a record for // a 404 with that SEF. If so, we will "upgrade" the 404 record to a // normal non-sef/sef pair $dbUrlId = empty($dbUrlId) ? 0 : intval($dbUrlId); if ($sefConfig->shLog404Errors) { if ($nonSefUrlType == sh404SEF_URLTYPE_404 && !empty($dbUrlId)) { // we already have seen that it is a 404 $id = $dbUrlId; } elseif ($nonSefUrlType == sh404SEF_URLTYPE_404) { $id = ShlDbHelper::selectResult('#__sh404sef_urls', 'id', array('oldurl' => $finalSefUrl, 'newurl' => '')); } else { $id = null; } } else { $id = null; // if we are not logging 404 errors, then no need to check for } // previous hit of this page. if (!empty($id)) { // we found a 404 record matching the SEF url just created. We'll update that record // instead of creating a new one // need to update dateadd to 0, as otherwise this sef/non-sef pair will be seen as custom // this makes all such 404 errors 'disappear' from the 404 log, but no other solution ShlDbHelper::updateIn('#__sh404sef_urls', array('newurl' => $nonSefUrl, 'dateadd' => '0000-00-00'), 'id', array($id)); Sh404sefHelperCache::addSefUrlToCache($nonSefUrl, $finalSefUrl, sh404SEF_URLTYPE_AUTO); } else { // standard case: creation of a totally new sef/non-sef pair ShlDbHelper::insert('#__sh404sef_urls', array('oldurl' => $finalSefUrl, 'newurl' => $nonSefUrl, 'rank' => 0, 'dateadd' => '0000-00-00')); // store new sef/non-sef pair in memory cache Sh404sefHelperCache::addSefUrlToCache($nonSefUrl, $finalSefUrl, sh404SEF_URLTYPE_AUTO); // create shURL : get a shURL model, and ask url creation $model = ShlMvcModel_Base::getInstance('pageids', 'Sh404sefModel'); $model->createPageId($finalSefUrl, $nonSefUrl); } } } } } catch (Exception $e) { $finalSefUrl = ''; ShlSystem_Log::error('sh404sef', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, $e->getMessage()); } return $finalSefUrl; }
$catid = isset($catid) ? $catid : null; // optional prefix $shWeblinksName = shGetComponentPrefix($option); if (!empty($shWeblinksName) && $shWeblinksName != '/') { $title[] = $shWeblinksName; } // joomla content models $slugsModel = Sh404sefModelSlugs::getInstance(); $menuItemTitle = getMenuTitle(null, $view, isset($Itemid) ? $Itemid : null, '', $shLangName); $uncategorizedPath = $sefConfig->slugForUncategorizedWeblinks == shSEFConfig::COM_SH404SEF_UNCATEGORIZED_EMPTY ? '' : $menuItemTitle; $slugsArray = array(); if ($task == 'weblink.go') { // jumping to link target if (!empty($id)) { try { $weblinkDetails = ShlDbHelper::selectObject('#__weblinks', array('id', 'title', 'catid'), array('id' => $id)); $slugsArray[] = $weblinkDetails->title; } catch (Exception $e) { ShlSystem_Log::error('sh404sef', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, $e->getMessage()); $weblinksDetails = null; } if (!empty($weblinkDetails->catid)) { try { $title = $slugsModel->getCategorySlugArray('com_weblinks', $weblinkDetails->catid, $sefConfig->includeWeblinksCat, $sefConfig->useWeblinksCatAlias, $insertId = false, $uncategorizedPath, $shLangName); } catch (Exception $e) { ShlSystem_Log::error('sh404sef', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, $e->getMessage()); } $title[] = '/'; } } else { $dosef = false;
/** * Returns the Joomla category for given id * * @param int $catid * @return string */ function _getCategories($catid, $useAlias = false) { $sefConfig =& SEFConfig::getConfig(); $database = ShlDbHelper::getDb(); $jfTranslate = $sefConfig->translateNames ? ', `id`' : ''; $cat_table = "#__categories"; $field = 'title'; if ($useAlias) { $field = 'alias'; } // Let's find the Joomla category name for given category ID $title = ''; if (isset($catid) && $catid != 0) { $catid = intval($catid); $query = "SELECT `{$field}` AS `title` {$jfTranslate} FROM `{$cat_table}` WHERE `id` = '{$catid}'"; $database->setQuery($query); $rows = $database->loadObjectList(); try { if ($database->getErrorNum()) { $msg = JText::_('Database error'); if (JDEBUG) { $msg .= ': ' . $database->stderr(); } throw new Exception($msg); } } catch (Exception $e) { JError::raiseError('JoomSEF Error', $e->getMessage()); } if (@count($rows) > 0 && !empty($rows[0]->title)) { $title = $rows[0]->title; } } return $title; }
function shGetJSVideoTitle($id, $option, $shLangName) { $sefConfig =& Sh404sefFactory::getConfig(); try { $result = ShlDbHelper::selectObject('#__community_videos', array('id', 'title', 'category_id'), array('id' => $id)); } catch (Exception $e) { ShlSystem_Log::error('sh404sef', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, $e->getMessage()); } $videoName = ($sefConfig->shJSInsertVideoId ? $id . $sefConfig->replacement : '') . $result->title; // optionnally insert video category if ($sefConfig->shJSInsertVideoCat) { $title = array(shGetJSVideoCategoryTitle($result->category_id, $option, $shLangName), $videoName); } else { $title = array($videoName); } return $title; }
/** * Creates a record in the database, based * on data read from import file * * @param array $header an array of fields, as built from the header line * @param string $line raw record obtained from import file */ protected function _createRecord($header, $line) { // extract the record $line = $this->_lineToArray($line); // get table object to store record $model = ShlMvcModel_Base::getInstance('editurl', 'Sh404sefModel'); // bind table to current record $record = array(); $record['oldurl'] = $line[1]; $record['newurl'] = $line[2]; if ($record['newurl'] == '__ Homepage __') { $record['newurl'] = sh404SEF_HOMEPAGE_CODE; } $record['cpt'] = $line[3]; $record['rank'] = $line[4]; $record['dateadd'] = $line[5]; $record['metatitle'] = $line[6]; $record['metadesc'] = $line[7]; $record['metakey'] = $line[8]; $record['metalang'] = $line[9]; $record['metarobots'] = $line[10]; // find if there is already an url record for this non-sef url. If so // we want the imported record to overwrite the existing one. // while makinf sure we're doing that with the main url, not one of the duplicates $existingRecords = $model->getByAttr(array('newurl' => $record['newurl'], 'oldurl' => $record['oldurl'])); if (!empty($existingRecords)) { $existingRecord = $existingRecords[0]; // getByAttr always returns an array // use the existing id, this will be enought to override existing record when saving $record['id'] = $existingRecord->id; // ensure consistency : delete the remaining records, though there is no reason // there can be more than one record with same SEF AND same SEF array_shift($existingRecords); if (!empty($existingRecords)) { ShlDbHelper::deleteIn('#__sh404sef_urls', 'id', $existingRecords, ShlDbHelper::INTEGER); } } else { $record['id'] = 0; } // find if we already have a meta data record for this non-sef url // as we want to update it if so, instead of creating a new record $metasModel = ShlMvcModel_Base::getInstance('metas', 'Sh404sefModel'); $existingMetas = $metasModel->getByAttr(array('newurl' => $record['newurl'])); if (!empty($existingMetas)) { $existingMeta = $existingMetas[0]; // getByAttr always returns an array // use the existing id, this will be enought to override existing record when saving $record['meta_id'] = $existingMeta->id; } else { $record['meta_id'] = 0; } // for aliases, we don't import them here, but we need to create a dummy // record so as to preserve possible pre-existing aliases for the same non-sef url $aliasesModel = ShlMvcModel_Base::getInstance('editalias', 'Sh404sefModel'); $existingAliases = $aliasesModel->getByAttr(array('newurl' => $record['newurl'])); $record['shAliasList'] = ''; if (!empty($existingAliases)) { foreach ($existingAliases as $existingAlias) { // build up a text list, just as if we were to edit aliases // as this is what the model expect to receive $record['shAliasList'] .= $existingAlias->alias . "\n"; } } // save record : returns the record id, so failure is when 0 is returned $savedId = $model->save($record, sh404SEF_URLTYPE_AUTO); if (empty($savedId)) { // rethrow a more appropriate error message throw new Sh404sefExceptionDefault(JText::sprintf('COM_SH404SEF_IMPORT_ERROR_INSERTING_INTO_DB', $line[0])); } }
function shDoTitleTags(&$buffer) { // Replace TITLE and DESCRIPTION and KEYWORDS if (empty($buffer)) { return; } global $shCustomTitleTag, $shCustomDescriptionTag, $shCustomKeywordsTag, $shCustomRobotsTag, $shCustomLangTag, $shCanonicalTag; $database = ShlDbHelper::getDb(); $shPageInfo =& Sh404sefFactory::getPageInfo(); $sefConfig =& Sh404sefFactory::getConfig(); $document = JFactory::getDocument(); $headData = $document->getHeadData(); // V 1.2.4.t protect against error if using shCustomtags without sh404SEF activated // this should not happen, so we simply do nothing if (!isset($sefConfig) || empty($shPageInfo->currentNonSefUrl)) { return; } // check if there is a manually created set of tags from tags file // need to get them from DB if ($sefConfig->shMetaManagementActivated) { shIncludeMetaPlugin(); // is this homepage ? set flag for future use // V 1.2.4.t make sure we have lang info and properly sorted params if (!preg_match('/(&|\\?)lang=[a-zA-Z]{2,3}/iuU', $shPageInfo->currentNonSefUrl)) { // no lang string, let's add default $shTemp = explode('-', $shPageInfo->currentLanguageTag); $shLangTemp = $shTemp[0] ? $shTemp[0] : 'en'; $shPageInfo->currentNonSefUrl .= '&lang=' . $shLangTemp; } $nonSef = shGetCurrentNonSef(); $isHome = $nonSef == shSortUrl(shCleanUpAnchor(Sh404sefFactory::getPageInfo()->homeLink)); $shCustomTags = shGetCustomMetaData($isHome ? sh404SEF_HOMEPAGE_CODE : $nonSef); // J! 2.5 finder canonical handling/hack $highlight = shGetURLVar($nonSef, 'highlight', null); if (!empty($highlight) && empty($shCanonicalTag)) { $searchCanoNonSef = str_replace('?highlight=' . $highlight, '', $nonSef); $searchCanoNonSef = str_replace('&highlight=' . $highlight, '', $searchCanoNonSef); $shCanonicalTag = JRoute::_($searchCanoNonSef); } $tagsToInsert = ''; // group new tags insertion, better perf if (!empty($shCustomTags)) { $shCustomTitleTag = !empty($shCustomTags->metatitle) ? $shCustomTags->metatitle : $shCustomTitleTag; $shCustomDescriptionTag = !empty($shCustomTags->metadesc) ? $shCustomTags->metadesc : $shCustomDescriptionTag; $shCustomKeywordsTag = !empty($shCustomTags->metakey) ? $shCustomTags->metakey : $shCustomKeywordsTag; $shCustomRobotsTag = !empty($shCustomTags->metarobots) ? $shCustomTags->metarobots : $shCustomRobotsTag; $shCustomLangTag = !empty($shCustomTags->metalang) ? $shCustomTags->metalang : $shCustomLangTag; $shCanonicalTag = !empty($shCustomTags->canonical) ? $shCustomTags->canonical : $shCanonicalTag; } // then insert them in page if (empty($shCustomTitleTag)) { $shCustomTitleTag = $document->getTitle(); } if (!empty($shCustomTitleTag)) { $prepend = $isHome ? '' : $sefConfig->prependToPageTitle; $append = $isHome ? '' : $sefConfig->appendToPageTitle; $shPageInfo->pageTitle = htmlspecialchars(shCleanUpTitle($prepend . $shCustomTitleTag . $append), ENT_COMPAT, 'UTF-8'); $buffer = ShlSystem_Strings::pr('/\\<\\s*title\\s*\\>.*\\<\\s*\\/title\\s*\\>/isuU', '<title>' . $shPageInfo->pageTitle . '</title>', $buffer); $buffer = ShlSystem_Strings::pr('/\\<\\s*meta\\s+name\\s*=\\s*"title.*\\/\\>/isuU', '', $buffer); // remove any title meta } if (!is_null($shCustomDescriptionTag)) { $t = htmlspecialchars(shCleanUpDesc($shCustomDescriptionTag), ENT_COMPAT, 'UTF-8'); $shPageInfo->pageDescription = ShlSystem_Strings::pr('#\\$([0-9]*)#u', '\\\\$${1}', $t); if (strpos($buffer, '<meta name="description" content=') !== false) { $buffer = ShlSystem_Strings::pr('/\\<\\s*meta\\s+name\\s*=\\s*"description.*\\/\\>/isUu', '<meta name="description" content="' . $shPageInfo->pageDescription . '" />', $buffer); } else { $tagsToInsert .= "\n" . '<meta name="description" content="' . $shPageInfo->pageDescription . '" />'; } } else { // read Joomla! description if none set by us if (empty($shPageInfo->pageDescription)) { $shPageInfo->pageDescription = empty($headData['description']) ? '' : htmlspecialchars(shCleanUpDesc($headData['description']), ENT_COMPAT, 'UTF-8'); } } if (!is_null($shCustomKeywordsTag)) { $t = htmlspecialchars(shCleanUpDesc($shCustomKeywordsTag), ENT_COMPAT, 'UTF-8'); $shPageInfo->pageKeywords = ShlSystem_Strings::pr('#\\$([0-9]*)#u', '\\\\$${1}', $t); if (strpos($buffer, '<meta name="keywords" content=') !== false) { $buffer = ShlSystem_Strings::pr('/\\<\\s*meta\\s+name\\s*=\\s*"keywords.*\\/\\>/isUu', '<meta name="keywords" content="' . $shPageInfo->pageKeywords . '" />', $buffer); } else { $tagsToInsert .= "\n" . '<meta name="keywords" content="' . $shPageInfo->pageKeywords . '" />'; } } else { // read Joomla! description if none set by us if (empty($shPageInfo->pageKeywords)) { $shPageInfo->pageKeywords = empty($headData['metaTags']['standard']['keywords']) ? '' : htmlspecialchars(shCleanUpDesc($headData['metaTags']['standard']['keywords']), ENT_COMPAT, 'UTF-8'); } } if (!is_null($shCustomRobotsTag)) { $shPageInfo->pageRobotsTag = $shCustomRobotsTag; if (strpos($buffer, '<meta name="robots" content="') !== false) { $buffer = ShlSystem_Strings::pr('/\\<\\s*meta\\s+name\\s*=\\s*"robots.*\\/\\>/isUu', '<meta name="robots" content="' . $shCustomRobotsTag . '" />', $buffer); } else { if (!empty($shCustomRobotsTag)) { $tagsToInsert .= "\n" . '<meta name="robots" content="' . $shCustomRobotsTag . '" />'; } } } else { // read Joomla! description if none set by us if (empty($shPageInfo->pageRobotsTag)) { $shPageInfo->pageRobotsTag = empty($headData['metaTags']['standard']['robots']) ? '' : htmlspecialchars(shCleanUpDesc($headData['metaTags']['standard']['robots']), ENT_COMPAT, 'UTF-8'); } } if (!is_null($shCustomLangTag)) { $shLang = $shCustomLangTag; $shPageInfo->pageLangTag = $shCustomLangTag; if (strpos($buffer, '<meta http-equiv="Content-Language"') !== false) { $buffer = ShlSystem_Strings::pr('/\\<\\s*meta\\s+http-equiv\\s*=\\s*"Content-Language".*\\/\\>/isUu', '<meta http-equiv="Content-Language" content="' . $shCustomLangTag . '" />', $buffer); } else { $tagsToInsert .= "\n" . '<meta http-equiv="Content-Language" content="' . $shCustomLangTag . '" />'; } } // custom handling of canonical $canonicalPattern = '/\\<\\s*link[^>]+rel\\s*=\\s*"canonical[^>]+\\/\\>/isUu'; $matches = array(); $canonicalCount = preg_match_all($canonicalPattern, $buffer, $matches); // more than one canonical already: kill them all if ($canonicalCount > 1 && Sh404sefFactory::getConfig()->removeOtherCanonicals) { $buffer = ShlSystem_Strings::pr($canonicalPattern, '', $buffer); $canonicalCount = 0; } // more than one and J3: must be the one inserted by J3 SEF plugin if ($canonicalCount > 0 && Sh404sefFactory::getConfig()->removeOtherCanonicals && version_compare(JVERSION, '3.0', 'ge')) { // kill it, if asked to $buffer = ShlSystem_Strings::pr($canonicalPattern, '', $buffer); $canonicalCount = 0; } // if there' a custom canonical for that page, insert it, or replace any existing ones if (!empty($shCanonicalTag) && $canonicalCount == 0) { // insert a new canonical $tagsToInsert .= "\n" . '<link href="' . htmlspecialchars($shCanonicalTag, ENT_COMPAT, 'UTF-8') . '" rel="canonical" />' . "\n"; } else { if (!empty($shCanonicalTag)) { // replace existing canonical $buffer = ShlSystem_Strings::pr($canonicalPattern, '<link href="' . htmlspecialchars($shCanonicalTag, ENT_COMPAT, 'UTF-8') . '" rel="canonical" />', $buffer); } } // insert all tags in one go if (!empty($tagsToInsert)) { $buffer = shInsertCustomTagInBuffer($buffer, '<head>', 'after', $tagsToInsert, 'first'); } // remove Generator tag if ($sefConfig->shRemoveGeneratorTag) { $buffer = ShlSystem_Strings::pr('/<meta\\s*name="generator"\\s*content=".*\\/>/isUu', '', $buffer); } // put <h1> tags around content elements titles if ($sefConfig->shPutH1Tags) { if (strpos($buffer, 'class="componentheading') !== false) { $buffer = ShlSystem_Strings::pr('/<div class="componentheading([^>]*)>\\s*(.*)\\s*<\\/div>/isUu', '<div class="componentheading$1><h1>$2</h1></div>', $buffer); $buffer = ShlSystem_Strings::pr('/<td class="contentheading([^>]*)>\\s*(.*)\\s*<\\/td>/isUu', '<td class="contentheading$1><h2>$2</h2></td>', $buffer); } else { // replace contentheading by h1 $buffer = ShlSystem_Strings::pr('/<td class="contentheading([^>]*)>\\s*(.*)\\s*<\\/td>/isUu', '<td class="contentheading$1><h1>$2</h1></td>', $buffer); } } // version x : if multiple h1 headings, replace them by h2 if ($sefConfig->shMultipleH1ToH2 && substr_count(JString::strtolower($buffer), '<h1>') > 1) { $buffer = str_replace('<h1>', '<h2>', $buffer); $buffer = str_replace('<H1>', '<h2>', $buffer); $buffer = str_replace('</h1>', '</h2>', $buffer); $buffer = str_replace('</H1>', '</h2>', $buffer); } // V 1.3.1 : replace outbounds links by internal redirects if (sh404SEF_REDIRECT_OUTBOUND_LINKS) { $tmp = preg_replace_callback('/<\\s*a\\s*href\\s*=\\s*"(.*)"/isUu', 'shDoRedirectOutboundLinksCallback', $buffer); if (empty($tmp)) { ShlSystem_Log::error('shlib', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, 'RegExp failed: invalid character on page ' . Sh404sefFactory::getPageInfo()->currentSefUrl); } else { $buffer = $tmp; } } // V 1.3.1 : add symbol to outbounds links if ($sefConfig->shInsertOutboundLinksImage) { $tmp = preg_replace_callback("/<\\s*a\\s*href\\s*=\\s*(\"|').*(\"|')\\s*>.*<\\/a>/isUu", 'shDoInsertOutboundLinksImageCallback', $buffer); if (empty($tmp)) { ShlSystem_Log::error('shlib', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, 'RegExp failed: invalid character on page ' . Sh404sefFactory::getPageInfo()->currentSefUrl); } else { $buffer = $tmp; } } // fix homepage link when using Joomfish in non default languages, error in joomla mainmenu helper /* if (sh404SEF_PROTECT_AGAINST_BAD_NON_DEFAULT_LANGUAGE_MENU_HOMELINK && !shIsDefaultLang( $shPageInfo->currentLanguageTag)) { $badHomeLink = preg_quote(JURI::base()); $targetLang = explode( '-', $shPageInfo->currentLanguageTag); $goodHomeLink = rtrim(JURI::base(), '/') . $sefConfig->shRewriteStrings[$sefConfig->shRewriteMode] . $targetLang[0] . '/'; $buffer = preg_replace( '#<div class="module_menu(.*)href="' . $badHomeLink . '"#isU', '<div class="module_menu$1href="' . $goodHomeLink . '"', $buffer); $buffer = preg_replace( '#<div class="moduletable_menu(.*)href="' . $badHomeLink . '"#isU', '<div class="moduletable_menu$1href="' . $goodHomeLink . '"', $buffer); } */ // all done return $buffer; } }
public function getAliasesCount($which = 'auto') { switch (strtolower($which)) { // we want to read all automatic urls (include duplicates) case 'auto': try { $numberOfUrls = ShlDbHelper::count($this->_getTableName(), '*', array('type' => Sh404sefHelperGeneral::COM_SH404SEF_URLTYPE_ALIAS)); } catch (Exception $e) { $numberofUrls = 0; } break; // we want to read urls as per current selection input fields // ie : component, language, custom, ... // we want to read urls as per current selection input fields // ie : component, language, custom, ... case 'selected': $numberOfUrls = $this->getTotal(); break; default: $numberOfUrls = 0; break; } return intval($numberOfUrls); }
function shAddPaginationInfo($limit, $limitstart, $showall, $iteration, $url, $location, $shSeparator = null, $defaultListLimitValue = null) { $mainframe = JFactory::getApplication(); //echo 'Incoming pagination : ' . $url . ' | limit : ' . $limit . ' | start : ' . $limitstart . "\n"; $pageInfo =& Sh404sefFactory::getPageInfo(); // get page details gathered by system plugin $sefConfig =& Sh404sefFactory::getConfig(); $database = ShlDbHelper::getDb(); // get a default limit value, for urls where it's missing $listLimit = shGetDefaultDisplayNumFromURL($url, $includeBlogLinks = true); $defaultListLimit = is_null($defaultListLimitValue) ? shGetDefaultDisplayNumFromConfig($url, $includeBlogLinks = false) : $defaultListLimitValue; //echo 'Incoming pagination : $listLimit : ' . $listLimit . ' | $defaultListLimit : ' . $defaultListLimit . "\n"; // clean suffix and index file before starting to add things to the url // clean suffix if (strpos($url, 'option=com_content') !== false && strpos($url, 'format=pdf') !== false) { $shSuffix = '.pdf'; } else { $shSuffix = $sefConfig->suffix; } $suffixLength = JString::strLen($shSuffix); if (!empty($shSuffix) && $shSuffix != '/' && JString::substr($location, -$suffixLength) == $shSuffix) { $location = JString::substr($location, 0, JString::strlen($location) - $suffixLength); } // clean index file if ($sefConfig->addFile && (empty($shSuffix) || JString::subStr($location, -$suffixLength) != $shSuffix)) { $indexFileLength = JString::strlen($sefConfig->addFile); if ($sefConfig->addFile != '/' && JString::substr($location, -$indexFileLength) == $sefConfig->addFile) { $location = JString::substr($location, 0, JString::strlen($location) - $indexFileLength); } } // do we have a trailing slash ? if (empty($shSeparator)) { $shSeparator = JString::substr($location, -1) == '/' ? '' : '/'; } if (!empty($limit) && is_numeric($limit)) { $pagenum = intval($limitstart / $limit); $pagenum++; } else { if (!isset($limit) && !empty($limitstart)) { // only limitstart if (strpos($url, 'option=com_content') !== false && strpos($url, 'view=article') !== false) { $pagenum = intval($limitstart + 1); // multipage article } else { $pagenum = intval($limitstart / $listLimit) + 1; // blogs, tables, ... } } else { $pagenum = $iteration; } } // Make sure we do not end in infite loop here. if ($pagenum < $iteration) { $pagenum = $iteration; } // shumisha added to handle table-category and table-section which may have variable number of items per page // There still will be a problem with filter, which may reduce the total number of items. Thus the item we are looking for if ($sefConfig->alwaysAppendItemsPerPage || strpos($url, 'option=com_virtuemart') && $sefConfig->shVmUsingItemsPerPage) { $shMultPageLength = $sefConfig->pagerep . (empty($limit) ? $listLimit : $limit); } else { $shMultPageLength = ''; } // shumisha : modified to add # of items per page to URL, for table-category or section-category if (!empty($sefConfig->pageTexts[$pageInfo->currentLanguageTag]) && false !== strpos($sefConfig->pageTexts[$pageInfo->currentLanguageTag], '%s')) { $page = str_replace('%s', $pagenum, $sefConfig->pageTexts[$pageInfo->currentLanguageTag]) . $shMultPageLength; } else { $page = $sefConfig->pagerep . $pagenum . $shMultPageLength; } // V 1.2.4.t special processing to replace page number by headings $shPageNumberWasReplaced = false; if (strpos($url, 'option=com_content') !== false && strpos($url, 'view=article') !== false && !empty($limitstart)) { // this is multipage article - limitstart instead of limit in J1.5 if ($sefConfig->shMultipagesTitle) { parse_str($url, $shParams); if (!empty($shParams['id'])) { $shPageTitle = ''; try { $contentElement = ShlDbHelper::selectObject('#__content', array('id', 'fulltext', 'introtext'), array('id' => $shParams['id'])); } catch (Exception $e) { JError::raise(E_ERROR, 500, $e->getMessage()); } $contentText = $contentElement->introtext . $contentElement->fulltext; if (!empty($contentElement) && strpos($contentText, 'class="system-pagebreak') !== false) { // search for mospagebreak tags // copied over from pagebreak plugin // expression to search for $regex = '#<hr([^>]*)class=(\\"|\')system-pagebreak(\\"|\')([^>]*)\\/>#iU'; // find all instances of mambot and put in $matches $shMatches = array(); preg_match_all($regex, $contentText, $shMatches, PREG_SET_ORDER); // adds heading or title to <site> Title if (empty($limitstart)) { // if first page use heading of first mospagebreak /* if ( $shMatches[0][2] ) { parse_str( html_entity_decode( $shMatches[0][2] ), $args ); if ( @$args['heading'] ) { $shPageTitle = stripslashes( $args['heading'] ); } }*/ } else { // for other pages use title of mospagebreak if ($limitstart > 0 && $shMatches[$limitstart - 1][1]) { $args = JUtility::parseAttributes($shMatches[$limitstart - 1][0]); if (@$args['title']) { $shPageTitle = $args['title']; } else { if (@$args['alt']) { $shPageTitle = $args['alt']; } else { // there is a page break, but no title. Use a page number $shPageTitle = str_replace('%s', $limitstart + 1, $sefConfig->pageTexts[$pageInfo->currentLanguageTag]); } } } } } if (!empty($shPageTitle)) { // found a heading, we should use that as a Title $location .= $shSeparator . titleToLocation($shPageTitle); } $shPageNumberWasReplaced = true; // always set the flag, otherwise we'll a Page-1 added } } else { // mutiple pages article, but we don't want to use smart title. // directly use limitstart $page = str_replace('%s', $limitstart + 1, $sefConfig->pageTexts[$pageInfo->currentLanguageTag]); } } // maybe this is a multipage with "showall=1" if (strpos($url, 'option=com_content') !== false && strpos($url, 'view=article') !== false && strpos($url, 'showall=1') !== false) { // this is multipage article with showall $tempTitle = JText::_('All Pages'); $location .= $shSeparator . titleToLocation($tempTitle); $shPageNumberWasReplaced = true; // always set the flag, otherwise we'll a Page-1 added } // make sure we remove bad characters $takethese = str_replace('|', '', $sefConfig->friendlytrim); $location = JString::trim($location, $takethese); // add page number if (!$shPageNumberWasReplaced && (!isset($limitstart) && (isset($limit) && $limit != 1 && $limit != $listLimit && $limit != $defaultListLimit) || !empty($limitstart))) { $location .= $shSeparator . $page; } // add suffix if (!empty($shSuffix) && !empty($location) && $location != '/' && JString::substr($location, -1) != '/') { $location = $shSuffix == '/' ? $location . $shSuffix : str_replace($shSuffix, '', $location) . $shSuffix; } // add default index file if ($sefConfig->addFile) { // V 1.2.4.t if (empty($shSuffix) || !empty($shSuffix) && JString::subStr($location, -$suffixLength) != $shSuffix) { $location .= (JString::substr($location, -1) == '/' ? '' : '/') . $sefConfig->addFile; } } return JString::ltrim($location, '/'); }
switch ($task) { case 'task1': case 'task2': $dosef = false; // these tasks do not require SEF URL break; default: $title[] = $sh_LANG[$shLangIso]['COM_SH404SEF_VIEW_SAMPLE']; // insert a 'View sample' string, // according to language // only if you have defined the if (!empty($sampleId)) { // fetch some data about the content try { // using shLib database helper is J2.x/J3.x safe $sampleTitle = ShlDbHelper::selectObject('#__sample_names', array('id', 'title'), array('id' => $sampleId)); } catch (Exception $e) { ShlSystem_Log::error('sh404sef', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, $e->getMessage()); } if ($sampleTitle) { // if we found a title for this element $title[] = $sampleTitle->title; // insert it in URL array shRemoveFromGETVarsList('sampleId'); // remove sampleId var from GET vars list // as we have found a text equivalent shMustCreatePageId('set', true); // NEW: ask sh404sef to create a short URL for this SEF URL (pageId) } } shRemoveFromGETVarsList('task');
$view = isset($view) ? $view : null; $slugsModel = Sh404sefModelSlugs::getInstance(); switch ($view) { case 'newsfeed': if (!empty($catid)) { // V 1.2.4.q try { $title = $slugsModel->getCategorySlugArray('com_newsfeeds', $catid, shSEFConfig::CAT_ALL_NESTED_CAT, $useAlias = false, $insertId = false, $menuItemTitle = '', $shLangName); } catch (Exception $e) { ShlSystem_Log::error('sh404sef', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, $e->getMessage()); $dosef = false; } } if (!empty($id)) { try { $rows = ShlDbHelper::selectObjectList('#__newsfeeds', array('name', 'id'), array('id' => $id)); } catch (Exception $e) { ShlSystem_Log::error('sh404sef', '%s::%s::%d: %s', __CLASS__, __METHOD__, __LINE__, $e->getMessage()); JError::raiseError(500, $e->getMessage()); } if (@count($rows) > 0) { if (!empty($rows[0]->name)) { $title[] = $rows[0]->name; } } } else { $title[] = '/'; } // V 1.2.4.s break; case 'category':