Example #1
0
bool ImageDesignManager::validatePalette(PaletteColorCustomizationVariable* palette, int value, int skillLevel) {
	String paletteFileName = palette->getPaletteFileName();
	int idx = paletteFileName.lastIndexOf("/");

	if (idx != -1) {
		String paletteName = paletteFileName.subString(idx + 1);
		paletteName = paletteName.subString(0, paletteName.indexOf("."));

		//info("palette name = " + paletteName, true);

		PaletteData* data = CustomizationIdManager::instance()->getPaletteData(paletteName);

		if (data == NULL) {
			//error("could not find palette data for " + paletteName);
		} else {
			int maxIndex;

			switch (skillLevel) {
			case -1:
				maxIndex = data->getCreationIndexes();
				break;
			case 0:
				maxIndex = data->getIdNoviceIndexes();
				break;
			case 1:
				maxIndex = data->getIdLevel1Indexes();
				break;
			case 2:
				maxIndex = data->getIdLevel2Indexes();
				break;
			case 3:
				maxIndex = data->getIdLevel3Indexes();
				break;
			case 4:
				maxIndex = data->getIdLevel4Indexes();
				break;
			case 5:
				maxIndex = data->getIdMasterIndexes();
				break;
			default:
				maxIndex = -1;
				break;
			}

			if (value >= maxIndex || value < 0) {
				instance()->error("value for " + paletteFileName + " value " + value + " outside bound " + String::valueOf(maxIndex));

				return false;
			} else {
				//info(name + " value " + String::valueOf(val) + " inside bound " + String::valueOf(maxIndex) + " for " + name , true);
			}
		}
	}

	return true;
}
Example #2
0
bool String::filenameIsAbsolutePath(const char* szText)
{
  String sText = szText;
  return 
#if defined(WIN32)
      sText.subString(1, 1) == ":" || sText.startsWith("/") || sText.subString(0, 2) == String_FILEPATHSEPARATOR String_FILEPATHSEPARATOR
#else
      sText.startsWith(String_FILEPATHSEPARATOR);
#endif
    ;
}
Example #3
0
//------------------------------------------------------------------------------
// FUNCTION: isHostAddress
//
// REMARKS: Verify if host is address
//
// PARAMETERS:  [IN] host -> string containing the host name or address
//
// RETURN: TRUE if host address, FALSE otherwise
//------------------------------------------------------------------------------
Boolean NTPService::isHostAddress(String host) {
    int ps;
    String strValue;
    Boolean ok = false;
    
    ps = host.find(".");
    if(ps > 0) {
        strValue.assign(host.subString(0, ps - 1));
        ok = (atoi(strValue.getCString()) > 0);
    }
    return ok;
}
void FireworkObjectImplementation::fillAttributeList(AttributeListMessage* alm, CreatureObject* object) {
	TangibleObjectImplementation::fillAttributeList(alm, object);

	ManagedReference<FireworkObject*> firework = _this.getReferenceUnsafeStaticCast();

	if (firework == NULL)
		return;

	DataObjectComponent* data = firework->getDataObjectComponent()->get();

	if (data == NULL || !data->isFireworkShowData()) {
		String effect = "@firework_n:" + fireworkObject.subString(fireworkObject.lastIndexOf("/") + 1, fireworkObject.lastIndexOf("."));
		alm->insertAttribute("@obj_attr_n:pattern", effect);
	} else {
		FireworkShowDataComponent* fireworkShowData = cast<FireworkShowDataComponent*>(data);

		if (fireworkShowData == NULL)
			return;

		alm->insertAttribute("examine_hoppersize", firework->getCapacity());

		int totalFireworks = fireworkShowData->getTotalFireworkCount();
		alm->insertAttribute("blank_entry", "");
		alm->insertAttribute("length", "\\#pcontrast2 " + String::valueOf(totalFireworks) + " Fireworks");

		for (int i = 0; i < totalFireworks; i++) {
			ManagedReference<FireworkObject*> firework = fireworkShowData->getFirework(i);
			if (firework == NULL)
				continue;
			String fireworkObj = firework->getFireworkObjectPath();
			String effect = "@firework_n:" + fireworkObj.subString(fireworkObj.lastIndexOf("/") + 1, fireworkObj.lastIndexOf("."));
			alm->insertAttribute("pattern", effect);
		}

	}

}
Example #5
0
// check the phrase lists
void NaughtyFilter::checkphrase(char *file, off_t filelen, const String *url, const String *domain,
	unsigned int filtergroup, unsigned int phraselist, int limit, bool searchterms)
{
	int weighting = 0;
	int cat;
	std::string weightedphrase;
	
	// checkme: translate this?
	String currcat("Embedded URLs");

	// found categories list & reusable iterators
	std::map<int, listent> listcategories;

	// check for embedded references to banned sites/URLs.
	// have regexes that check for URLs in pages (look for attributes (src, href, javascript location)
	// or look for protocol strings (in which case, incl. ftp)?) and extract them.
	// then check the extracted list against the banned site/URL lists.
	// ADs category lists do not want to add to the possibility of a site being banned.
	// Exception lists are not checked.
	// Do not do full-blown category retrieval/duplicate checking; simply add the
	// "Embedded URLs" category.
	// Put a warning next to the option in the config file that this will take lots of CPU.
	// Support phrase mode 1/2 distinction (duplicate sites/URLs).
	// Have weight configurable per filter group, not globally or with a list directive - 
	//   a weight of 0 will disable the option, effectively making this functionality per-FG itself.

	// todo: if checkphrase is passed the domain & existing URL, it can create full URLs from relative ones.
	// if a src/href URL starts with a /, append it to the domain; otherwise, append it to the existing URL.
	// chop off anything after a ?, run through realPath, then put through the URL lists.

#ifdef HAVE_PCRE
	// if weighted phrases are enabled, and we have been passed a URL and domain, and embedded URL checking is enabled...
	// then check for embedded URLs!
	if (url != NULL && o.fg[filtergroup]->embedded_url_weight > 0) {
		std::map<int, listent>::iterator ourcat;
		bool catinited = false;
		std::map<String, unsigned int> found;
		std::map<String, unsigned int>::iterator founditem;

		String u;
		char* j;

		// check for absolute URLs
		if (absurl_re.match(file)) {
			// each match generates 2 results (because of the brackets in the regex), we're only interested in the first
#ifdef DGDEBUG
			std::cout << "Found " << absurl_re.numberOfMatches()/2 << " absolute URLs:" << std::endl;
#endif
			for (int i = 0; i < absurl_re.numberOfMatches(); i+=2) {
				// chop off quotes
				u = absurl_re.result(i);
				u = u.subString(1,u.length()-2);
#ifdef DGDEBUG
				std::cout << u << std::endl;
#endif
				if ((((j = o.fg[filtergroup]->inBannedSiteList(u)) != NULL) && !(o.lm.l[o.fg[filtergroup]->banned_site_list]->lastcategory.contains("ADs")))
					|| (((j = o.fg[filtergroup]->inBannedURLList(u)) != NULL) && !(o.lm.l[o.fg[filtergroup]->banned_url_list]->lastcategory.contains("ADs"))))
				{
					// duplicate checking
					// checkme: this should really be being done *before* we search the lists.
					// but because inBanned* methods do some cleaning up of their own, we don't know the form to check against.
					// we actually want these cleanups do be done before passing to inBanned*/inException* - this would
					// speed up ConnectionHandler a bit too.
					founditem = found.find(j);
					if ((o.fg[filtergroup]->weighted_phrase_mode == 2) && (founditem != found.end())) {
						founditem->second++;
					} else {
						// add the site to the found phrases list
						found[j] = 1;
						if (weightedphrase.length() == 0)
							weightedphrase = "[";
						else
							weightedphrase += " ";
						weightedphrase += j;
						if (!catinited) {
							listcategories[-1] = listent(o.fg[filtergroup]->embedded_url_weight,currcat);
							ourcat = listcategories.find(-1);
							catinited = true;
						} else
							ourcat->second.weight += o.fg[filtergroup]->embedded_url_weight;
					}
				}
			}
		}

		found.clear();

		// check for relative URLs
		if (relurl_re.match(file)) {
			// we don't want any parameters on the end of the current URL, since we append to it directly
			// when forming absolute URLs from relative ones. we do want a / on the end, too.
			String currurl(*url);
			if (currurl.contains("?"))
				currurl = currurl.before("?");
			if (currurl[currurl.length()-1] != '/')
				currurl += "/";

			// each match generates 2 results (because of the brackets in the regex), we're only interested in the first
#ifdef DGDEBUG
			std::cout << "Found " << relurl_re.numberOfMatches()/2 << " relative URLs:" << std::endl;
#endif
			for (int i = 0; i < relurl_re.numberOfMatches(); i+=2) {
				u = relurl_re.result(i);
				
				// can't find a way to negate submatches in PCRE, so it is entirely possible
				// that some absolute URLs have made their way into this list. we don't want them.
				if (u.contains("://"))
					continue;

#ifdef DGDEBUG
				std::cout << u << std::endl;
#endif
				// remove src/href & quotes
				u = u.after("=");
				u.removeWhiteSpace();
				u = u.subString(1,u.length()-2);
				
				// create absolute URL
				if (u[0] == '/')
					u = (*domain) + u;
				else
					u = currurl + u;
#ifdef DGDEBUG
				std::cout << "absolute form: " << u << std::endl;
#endif
				if ((((j = o.fg[filtergroup]->inBannedSiteList(u)) != NULL) && !(o.lm.l[o.fg[filtergroup]->banned_site_list]->lastcategory.contains("ADs")))
					|| (((j = o.fg[filtergroup]->inBannedURLList(u)) != NULL) && !(o.lm.l[o.fg[filtergroup]->banned_url_list]->lastcategory.contains("ADs"))))
				{
					// duplicate checking
					// checkme: this should really be being done *before* we search the lists.
					// but because inBanned* methods do some cleaning up of their own, we don't know the form to check against.
					// we actually want these cleanups do be done before passing to inBanned*/inException* - this would
					// speed up ConnectionHandler a bit too.
					founditem = found.find(j);
					if ((o.fg[filtergroup]->weighted_phrase_mode == 2) && (founditem != found.end())) {
						founditem->second++;
					} else {
						// add the site to the found phrases list
						found[j] = 1;
						if (weightedphrase.length() == 0)
							weightedphrase = "[";
						else
							weightedphrase += " ";
						weightedphrase += j;
						if (!catinited) {
							listcategories[-1] = listent(o.fg[filtergroup]->embedded_url_weight,currcat);
							ourcat = listcategories.find(-1);
							catinited = true;
						} else
							ourcat->second.weight += o.fg[filtergroup]->embedded_url_weight;
					}
				}
			}
		}
		if (catinited) {
			weighting = ourcat->second.weight;
			weightedphrase += "]";
#ifdef DGDEBUG
			std::cout << weightedphrase << std::endl;
			std::cout << "score from embedded URLs: " << ourcat->second.weight << std::endl;
#endif
		}
	}
#endif

	std::string bannedphrase;
	std::string exceptionphrase;
	String bannedcategory;
	int type, index, weight, time;
	bool allcmatched = true, bannedcombi = false;
	std::string s1;

	// this line here searches for phrases contained in the list - the rest of the code is all sorting
	// through it to find the categories, weightings, types etc. of what has actually been found.
	std::map<std::string, std::pair<unsigned int, int> > found;
	o.lm.l[phraselist]->graphSearch(found, file, filelen);

	// cache reusable iterators
	std::map<std::string, std::pair<unsigned int, int> >::iterator foundend = found.end();
	std::map<std::string, std::pair<unsigned int, int> >::iterator foundcurrent;

	// look for combinations first
	//if banned must wait for exception later
	std::string combifound;
	std::string combisofar;

	std::vector<int>::iterator combicurrent = o.lm.l[phraselist]->combilist.begin();
	std::map<int, listent>::iterator catcurrent;
	int lowest_occurrences = 0;

	while (combicurrent != o.lm.l[phraselist]->combilist.end()) {
		// Grab the current combination phrase part
		index = *combicurrent;
		// Do stuff if what we have is an end marker (end of one list of parts)
		if (index == -2) {
			// Were all the parts in this combination matched?
			if (allcmatched) {
				type = *(++combicurrent);
				// check this time limit against the list of time limits
				time = *(++combicurrent);
				if (not (o.lm.l[phraselist]->checkTimeAtD(time))) {
					// nope - so don't take any notice of it
#ifdef DGDEBUG
					combicurrent++;
					cat = (*++combicurrent);
					std::cout << "Ignoring combi phrase based on time limits: " << combisofar << "; "
						<< o.lm.l[phraselist]->getListCategoryAtD(cat) << std::endl;
#else
					combicurrent += 2;
#endif
					combisofar = "";
				}
				else if (type == -1) {	// combination exception
					isItNaughty = false;
					isException = true;
					// Combination exception phrase found:
					// Combination exception search term found:
					message_no = searchterms ? 456 : 605;
					whatIsNaughtyLog = o.language_list.getTranslation(message_no);
					whatIsNaughtyLog += combisofar;
					whatIsNaughty = "";
					++combicurrent;
					cat = *(++combicurrent);
					whatIsNaughtyCategories = o.lm.l[phraselist]->getListCategoryAtD(cat);
					return;
				}
				else if (type == 1) {	// combination weighting
					weight = *(++combicurrent);
					weighting += weight * (o.fg[filtergroup]->weighted_phrase_mode == 2 ? 1 : lowest_occurrences);
					if (weight > 0) {
						cat = *(++combicurrent);
						//category index -1 indicates an uncategorised list
						if (cat >= 0) {
							//don't output duplicate categories
							catcurrent = listcategories.find(cat);
							if (catcurrent != listcategories.end()) {
								catcurrent->second.weight += weight * (o.fg[filtergroup]->weighted_phrase_mode == 2 ? 1 : lowest_occurrences);
							} else {
								currcat = o.lm.l[phraselist]->getListCategoryAtD(cat);
								listcategories[cat] = listent(weight,currcat);
							}
						}
					} else {
						// skip past category for negatively weighted phrases
						combicurrent++;
					}
					if (weightedphrase.length() > 0) {
						weightedphrase += "+";
					}
					weightedphrase += "(";
					if (weight < 0) {
						weightedphrase += "-" + combisofar;
					} else {
						weightedphrase += combisofar;
					}
#ifdef DGDEBUG
					std::cout << "found combi weighted phrase ("<< o.fg[filtergroup]->weighted_phrase_mode << "): "
						<< combisofar << " x" << lowest_occurrences << " (per phrase: "
						<< weight << ", calculated: "
						<< (weight * (o.fg[filtergroup]->weighted_phrase_mode == 2 ? 1 : lowest_occurrences)) << ")"
						<< std::endl;
#endif

					weightedphrase += ")";
					combisofar = "";
				}
				else if (type == 0) {	// combination banned
					bannedcombi = true;
					combifound += "(" + combisofar + ")";
					combisofar = "";
					combicurrent += 2;
					cat = *(combicurrent);
					bannedcategory = o.lm.l[phraselist]->getListCategoryAtD(cat);
				}
			} else {
				// We had an end marker, but not all the parts so far were matched.
				// Reset the match flag ready for the next chain, and advance to its first part.
				allcmatched = true;
				combicurrent += 4;
				lowest_occurrences = 0;
			}
		} else {
			// We didn't get an end marker - just an individual part.
			// If all parts in the current chain have been matched so far, look for this one as well.
			if (allcmatched) {
				s1 =o.lm.l[phraselist]->getItemAtInt(index);
				if ((foundcurrent = found.find(s1)) == foundend) {
					allcmatched = false;
					combisofar = "";
				} else {
					if (combisofar.length() > 0) {
						combisofar += ", ";
					}
					combisofar += s1;
					// also track lowest number of times any one part occurs in the text
					// as this will correspond to the number of times the whole chain occurs
					if ((lowest_occurrences == 0) || (lowest_occurrences > foundcurrent->second.second)) {
						lowest_occurrences = foundcurrent->second.second;
					}
				}
			}
		}
		// Advance to the next part in the current chain
		combicurrent++;
	}

	// even if we already found a combi ban, we must still wait; there may be non-combi exceptions to follow

	// now check non-combi phrases
	foundcurrent = found.begin();
	while (foundcurrent != foundend) {
		// check time for current phrase
		if (not o.lm.l[phraselist]->checkTimeAt(foundcurrent->second.first)) {
#ifdef DGDEBUG
			std::cout << "Ignoring phrase based on time limits: "
				<< foundcurrent->first << ", "
				<< o.lm.l[phraselist]->getListCategoryAt(foundcurrent->second.first) << std::endl;
#endif
			foundcurrent++;
			continue;
		}
		// 0=banned, 1=weighted, -1=exception, 2=combi, 3=weightedcombi
		type = o.lm.l[phraselist]->getTypeAt(foundcurrent->second.first);
		if (type == 0) {
			// if we already found a combi ban, we don't need to know this stuff
			if (!bannedcombi) {
				isItNaughty = true;
				bannedphrase = foundcurrent->first;
				bannedcategory = o.lm.l[phraselist]->getListCategoryAt(foundcurrent->second.first, &cat);
			}
		}
		else if (type == 1) {
			// found a weighted phrase - either add one lot of its score, or one lot for every occurrence, depending on phrase filtering mode
			weight = o.lm.l[phraselist]->getWeightAt(foundcurrent->second.first) * (o.fg[filtergroup]->weighted_phrase_mode == 2 ? 1 : foundcurrent->second.second);
			weighting += weight;
			if (weight > 0) {
				currcat = o.lm.l[phraselist]->getListCategoryAt(foundcurrent->second.first, &cat);
				if (cat >= 0) {
					//don't output duplicate categories
					catcurrent = listcategories.find(cat);
					if (catcurrent != listcategories.end()) {
						// add one or N times the weight to this category's score
						catcurrent->second.weight += weight * (o.fg[filtergroup]->weighted_phrase_mode == 2 ? 1 : foundcurrent->second.second);
					} else {
						listcategories[cat] = listent(weight,currcat);
					}
				}
			}

			if (o.show_weighted_found) {
				if (weightedphrase.length() > 0) {
					weightedphrase += "+";
				}
				if (weight < 0) {
					weightedphrase += "-";
				}

				weightedphrase += foundcurrent->first;
			}
#ifdef DGDEBUG
			std::cout << "found weighted phrase ("<< o.fg[filtergroup]->weighted_phrase_mode << "): "
				<< foundcurrent->first << " x" << foundcurrent->second.second << " (per phrase: "
				<< o.lm.l[phraselist]->getWeightAt(foundcurrent->second.first)
				<< ", calculated: " << weight << ")" << std::endl;
#endif
		}
		else if (type == -1) {
			isException = true;
			isItNaughty = false;
			// Exception phrase found:
			// Exception search term found:
			message_no = searchterms ? 457 : 604;
			whatIsNaughtyLog = o.language_list.getTranslation(message_no);
			whatIsNaughtyLog += foundcurrent->first;
			whatIsNaughty = "";
			whatIsNaughtyCategories = o.lm.l[phraselist]->getListCategoryAt(foundcurrent->second.first, NULL);
			return;  // no point in going further
		}
		foundcurrent++;
	}

#ifdef DGDEBUG
	std::cout << "WEIGHTING: " << weighting << std::endl;
#endif

	// store the lowest negative weighting or highest positive weighting out of all filtering runs, preferring to store positive weightings.
	if ((weighting < 0 && naughtiness <= 0 && weighting < naughtiness) || (naughtiness >= 0 && weighting > naughtiness) || (naughtiness < 0 && weighting > 0) ) {
		naughtiness = weighting;
	}

#ifdef DGDEBUG
	std::cout << "NAUGHTINESS: " << naughtiness << std::endl;
#endif

	// *now* we can safely get down to the whole banning business!

	if (bannedcombi) {
		isItNaughty = true;
		// Banned combination phrase found:
		// Banned combination search term found:
		message_no = searchterms ? 452: 400;
		whatIsNaughtyLog = o.language_list.getTranslation(message_no);
		whatIsNaughtyLog += combifound;
		// Banned combination phrase found.
		// Banned combination search term found.
		whatIsNaughty = o.language_list.getTranslation(searchterms ? 453 : 401);
		whatIsNaughtyCategories = bannedcategory.toCharArray();
		return;
	}

	if (isItNaughty) {
		// Banned phrase found:
		// Banned search term found:
		message_no = searchterms ? 450: 300;
		whatIsNaughtyLog = o.language_list.getTranslation(message_no);
		whatIsNaughtyLog += bannedphrase;
		// Banned phrase found.
		// Banned search term found.
		whatIsNaughty = o.language_list.getTranslation(searchterms ? 451 : 301);
		whatIsNaughtyCategories = bannedcategory.toCharArray();
		return;
	}

	if (weighting > limit) {
		isItNaughty = true;
		// Weighted phrase limit of
		// Weighted search term limit of
		message_no = searchterms ? 454: 401;
		whatIsNaughtyLog = o.language_list.getTranslation(message_no);
		whatIsNaughtyLog += String(limit).toCharArray();
		whatIsNaughtyLog += " : ";
		whatIsNaughtyLog += String(weighting).toCharArray();
		if (o.show_weighted_found) {
			whatIsNaughtyLog += " (";
			whatIsNaughtyLog += weightedphrase;
			whatIsNaughtyLog += ")";
		}
		// Weighted phrase limit exceeded.
		// Weighted search term limit exceeded.
		whatIsNaughty = o.language_list.getTranslation(searchterms ? 455 : 403);
		// Generate category list, sorted with highest scoring first.
		bool nonempty = false;
		bool belowthreshold = false;
		String categories;
		std::deque<listent> sortable_listcategories;
		catcurrent = listcategories.begin();
		while (catcurrent != listcategories.end()) {
			sortable_listcategories.push_back(catcurrent->second);
			catcurrent++;
		}
		std::sort(sortable_listcategories.begin(), sortable_listcategories.end());
		std::deque<listent>::iterator k = sortable_listcategories.begin();
		while (k != sortable_listcategories.end()) {
			// if category display threshold is in use, apply it
			if (!belowthreshold && (o.fg[filtergroup]->category_threshold > 0)
				&& (k->weight < o.fg[filtergroup]->category_threshold))
			{
				whatIsNaughtyDisplayCategories = categories.toCharArray();
				belowthreshold = true;
				usedisplaycats = true;
			}
			if (k->string.length() > 0) {
				if (nonempty) categories += ", ";
				categories += k->string;
				nonempty = true;
			}
			k++;
			// if category threshold is set to show only the top category,
			// everything after the first loop is below the threshold
			if (!belowthreshold && o.fg[filtergroup]->category_threshold < 0) {
				whatIsNaughtyDisplayCategories = categories.toCharArray();
				belowthreshold = true;
				usedisplaycats = true;
			}
		}
		whatIsNaughtyCategories = categories.toCharArray();
		return;
	}
	// whatIsNaughty is what is displayed in the browser
	// whatIsNaughtyLog is what is logged in the log file if at all
}
Boolean ClientAuthenticator::checkResponseHeaderForChallenge(
    Array<HTTPHeader> headers)
{
    //
    // Search for "WWW-Authenticate" header:
    //
    const char* authHeader;
    String authType;
    String authChallenge;
    String authRealm;

    if (!HTTPMessage::lookupHeader(
            headers, WWW_AUTHENTICATE, authHeader, false))
    {
        return false;
    }

   //
   // Parse the authentication challenge header
   //
   if (!_parseAuthHeader(authHeader, authType, authChallenge))
   {
       throw InvalidAuthHeader();
   }

   if (String::equal(authType, "Local"))
   {
       _authType = ClientAuthenticator::LOCAL;
       authRealm = _parseBasicRealm(authChallenge);
       if (authRealm.size() == 0)
           return false;
   }
   else if ( String::equal(authType, "Basic"))
   {
       _authType = ClientAuthenticator::BASIC;
       authRealm = _parseBasicRealm(authChallenge);
       if (authRealm.size() == 0)
           return false;
   }
   else if ( String::equal(authType, "Digest"))
   {
       _authType = ClientAuthenticator::DIGEST;
   }
   else if ( String::equal(authType, "Negotiate"))
   {
       _authType = ClientAuthenticator::NEGOTIATE;
#ifdef PEGASUS_NEGOTIATE_AUTHENTICATION
       _session->parseChallenge(authChallenge);
#endif
   }
   else
   {
       throw InvalidAuthHeader();
   }

   if (_challengeReceived)
   {
       // Do not respond to a challenge more than once.
       // Only Negotiate authentication can take multiple roundtrips,
       // but stop it when the server returns empty challenge.
       if (_authType != ClientAuthenticator::NEGOTIATE
               || authChallenge.size() == 0)
       {
           return false;
       }
   }

   _challengeReceived = true;

   if (_authType == ClientAuthenticator::LOCAL)
   {
       String filePath = authRealm;
       FileSystem::translateSlashes(filePath);

       // Check whether the directory is a valid pre-defined directory.
       //
       Uint32 index = filePath.reverseFind('/');

       if (index != PEG_NOT_FOUND)
       {
           String dirName = filePath.subString(0,index);

           if (!String::equal(dirName, String(PEGASUS_LOCAL_AUTH_DIR)))
           {
               // Refuse to respond to the challenge when the file is
               // not in the expected directory
               return false;
           }
       }

       _localAuthFile = authRealm;
   }

   return true;
}
Example #7
0
void TreeNode::xPathTestNode(const Array<String>& tokens, int tokenIndex, const Enumerator<TreeNode*>& enumerator, bool includeHiddenChildren, const NumberFormat* numberFormat)
{
	if (tokenIndex == tokens.getCount())
	{
		// If no further path-tokens are available, we are at the end of the path,
		// and have found a target-node to add to the result:
		enumerator.enumerate(this);
	}
	else
	{
		int nextTokenIndex = tokenIndex + 1;
		const String& token = tokens[tokenIndex];
		if (token == "..")
		{
			if (parent != NULL)
			{
				parent->xPathTestNode(tokens, nextTokenIndex, enumerator, includeHiddenChildren, numberFormat);
			}
			else
			{
				argumentError("XPath invalid for current tree!" ERROR_AT);
				return;
			}
		}
		else if (token == '.')
		{
			xPathTestNode(tokens, nextTokenIndex, enumerator, includeHiddenChildren, numberFormat);
		}
		else
		{
			int where = token.findFirst('[');
			if (where == String::END)
			{
				// If no [ was found:
				// For every child-node:
				int childCount = includeHiddenChildren == true ? getChildCountIncludingHiddenChildren() : getChildCount();
				for (int i = 0; i < childCount; ++i)
				{
					TreeNode* childNode = getChild(i);
					if (childNode->getName() == token || token == '*')
					{
						// If name of child-node is valid for the next path-token:
						childNode->xPathTestNode(tokens, nextTokenIndex, enumerator, includeHiddenChildren, numberFormat);
					}
				}
			}
			else
			{
				// If [ was found:
				String name = token.subString(0, where).trimTail();
				int countOfNodesWithMatchingName = 0;
				// For every child-node:
				int childCount = includeHiddenChildren == true ? getChildCountIncludingHiddenChildren() : getChildCount();
				for (int i = 0; i < childCount; ++i)
				{
					TreeNode* childNode = getChild(i);
					if (childNode->getName() == name || name == '*')
					{
						++countOfNodesWithMatchingName;

						// If name of child-node is valid for the next path-token,
						// get expression between [ and ]:
						String expression = token.subString(where + 1, token.findLast(']') - (where + 1));
						if (expression.beginsWith('@') == true)
						{
							// If we are dealing with an attribute:
							int equalPos = expression.findFirst('=');
							if (equalPos == String::END)
							{
								String attributeName = expression.subString(1);
								if (childNode->hasAttribute(attributeName) == true)
								{
									childNode->xPathTestNode(tokens, nextTokenIndex, enumerator, includeHiddenChildren, numberFormat);
								}
							}
							else
							{
								String attributeName = expression.subString(1, equalPos-1).trimTail();
								String value = expression.subString(equalPos + 1).trimFront();
								String attribute;
								if (getAttributeIfAvailable(attributeName, attribute, numberFormat) == true && attribute == value)
								{
									childNode->xPathTestNode(tokens, nextTokenIndex, enumerator, includeHiddenChildren, numberFormat);
								}
							}
						}
						else if (expression.isDec() == true)
						{
							// If we are dealing with a node-indexer:
							if (expression.parseInt() == countOfNodesWithMatchingName)
							{
								childNode->xPathTestNode(tokens, nextTokenIndex, enumerator, includeHiddenChildren, numberFormat);
							}
						}
						else
						{
							argumentError("Unsupported XPath expression: " + token + ERROR_AT);
						}

					} // if (childNode->getName() == name || name == '*')

				} // for (int i = 0; i < childCount; ++i)

			} // else if (where == String::END)

		} // else if (token == "..") else if if (token == '.')

	} // else if (tokenIndex == tokens.getLength())

}
Example #8
0
static void 
replace(String &s, unsigned int pos, unsigned int len, const String &r)
{
  String s1 = s.subString(0, pos) + r + s.subString(pos  + len);
  s = s1;
}