3 * =============================================================================
5 * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
35 #include "sm_stringutil.h"
37 #include "PluginSys.h"
38 #include "Translator.h"
39 #include "PlayerManager.h"
41 #define LADJUST 0x00000004 /* left adjustment */
42 #define ZEROPAD 0x00000080 /* zero (as opposed to blank) pad */
43 #define UPPERDIGITS 0x00000200 /* make alpha digits uppercase */
44 #define to_digit(c) ((c) - '0')
45 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
47 #define CHECK_ARGS(x) \
48 if ((arg+x) > args) { \
49 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "String formatted incorrectly - parameter %d (total %d)", arg, args); \
53 size_t CorePlayerTranslate(int client, char *buffer, size_t maxlength, const char *phrase, void **params)
58 err = g_pCorePhrases->GetTranslation(phrase, g_Translator.GetServerLanguage(), &pTrans);
59 if (err != Trans_Okay && g_Translator.GetServerLanguage() != CORELANG_ENGLISH)
61 err = g_pCorePhrases->GetTranslation(phrase, CORELANG_ENGLISH, &pTrans);
64 if (err != Trans_Okay)
66 return UTIL_Format(buffer, maxlength, "%s", phrase);
69 return g_Translator.Translate(buffer, maxlength, params, &pTrans);
72 inline bool TryTranslation(CPlugin *pl, const char *key, unsigned int langid, unsigned int langcount, Translation *pTrans)
74 TransError err = Trans_BadLanguage;
77 for (size_t i=0; i<langcount && err!=Trans_Okay; i++)
79 phrfl = g_Translator.GetFileByIndex(pl->GetLangFileByIndex(i));
80 err = phrfl->GetTranslation(key, langid, pTrans);
83 return (err == Trans_Okay) ? true : false;
86 size_t Translate(char *buffer, size_t maxlen, IPluginContext *pCtx, const char *key, cell_t target, const cell_t *params, int *arg, bool *error)
91 CPlugin *pl = (CPlugin *)g_PluginSys.FindPluginByContext(pCtx->GetContext());
92 size_t langcount = pl->GetLangFileCount();
93 void *new_params[MAX_TRANSLATE_PARAMS];
94 unsigned int max_params = 0;
97 if (target == LANG_SERVER)
99 langid = g_Translator.GetServerLanguage();
100 } else if ((target >= 1) && (target <= g_Players.GetMaxClients())) {
101 langid = g_Translator.GetClientLanguage(target);
103 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Translation failed: invalid client index %d", target);
107 if (!TryTranslation(pl, key, langid, langcount, &pTrans))
109 if (target != LANG_SERVER && langid != g_Translator.GetServerLanguage())
111 target = LANG_SERVER;
113 } else if (langid != LANGUAGE_ENGLISH) {
114 if (!TryTranslation(pl, key, LANGUAGE_ENGLISH, langcount, &pTrans))
116 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Language phrase \"%s\" not found", key);
120 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Language phrase \"%s\" not found", key);
125 max_params = pTrans.fmt_count;
129 /* Check if we're going to over the limit */
130 if ((*arg) + (max_params - 1) > (size_t)params[0])
132 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAMS_MAX,
133 "Translation string formatted incorrectly - missing at least %d parameters",
134 ((*arg + (max_params - 1)) - params[0])
139 /* Translate the parameters to raw pointers */
140 for (size_t i=0; i<max_params; i++)
142 pCtx->LocalToPhysAddr(params[*arg], reinterpret_cast<cell_t **>(&new_params[i]));
147 return g_Translator.Translate(buffer, maxlen, new_params, &pTrans);
153 //:TODO: review this code before we choose a license
155 void AddString(char **buf_p, size_t &maxlen, const char *string, int width, int prec)
159 static char nlstr[] = {'(','n','u','l','l',')','\0'};
171 for (size = 0; size < prec; size++)
173 if (string[size] == '\0')
179 while (string[size++]);
183 if (size > (int)maxlen)
196 while ((width-- > 0) && maxlen)
205 void AddFloat(char **buf_p, size_t &maxlen, double fval, int width, int prec)
220 // write the float number
225 text[digits++] = '0' + val % 10;
231 text[digits++] = '-';
236 while ((digits < width) && maxlen)
243 while ((digits--) && maxlen)
245 *buf++ = text[digits];
255 // write the fraction
257 while (digits < prec)
262 text[digits++] = '0' + val % 10;
265 if ((digits > 0) && maxlen)
270 for (prec = 0; maxlen && (prec < digits); prec++)
279 void AddUInt(char **buf_p, size_t &maxlen, unsigned int val, int width, int flags)
288 text[digits++] = '0' + val % 10;
294 if (!(flags & LADJUST))
296 while (digits < width && maxlen)
298 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
304 while (digits-- && maxlen)
306 *buf++ = text[digits];
313 while (width-- && maxlen)
315 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
323 void AddInt(char **buf_p, size_t &maxlen, int val, int width, int flags)
329 unsigned int unsignedVal;
335 /* we want the unsigned version */
336 unsignedVal = abs(val);
342 text[digits++] = '0' + unsignedVal % 10;
344 } while (unsignedVal);
348 text[digits++] = '-';
353 if (!(flags & LADJUST))
355 while ((digits < width) && maxlen)
357 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
363 while (digits-- && maxlen)
365 *buf++ = text[digits];
372 while (width-- && maxlen)
374 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
382 void AddHex(char **buf_p, size_t &maxlen, unsigned int val, int width, int flags)
390 if (flags & UPPERDIGITS)
392 hexadjust = 'A' - '9' - 1;
394 hexadjust = 'a' - '9' - 1;
400 digit = ('0' + val % 16);
406 text[digits++] = digit;
412 if (!(flags & LADJUST))
414 while (digits < width && maxlen)
416 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
422 while (digits-- && maxlen)
424 *buf++ = text[digits];
431 while (width-- && maxlen)
433 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
441 size_t gnprintf(char *buffer, size_t maxlen, const char *format, void **args)
443 if (!buffer || !maxlen)
457 size_t llen = maxlen - 1;
464 // run through the format string until we hit a '%' or '\0'
465 for (ch = *fmt; llen && ((ch = *fmt) != '\0') && (ch != '%'); fmt++)
470 if ((ch == '\0') || (llen <= 0))
478 // reset formatting state
497 while(is_digit((ch = *fmt++)))
499 n = 10 * n + (ch - '0');
501 prec = (n < 0) ? -1 : n;
522 n = 10 * n + (ch - '0');
524 } while(is_digit(ch));
534 char *c = (char *)args[arg];
543 int *value = (int *)args[arg];
544 AddInt(&buf_p, llen, *value, width, flags);
550 unsigned int *value = (unsigned int *)args[arg];
551 AddUInt(&buf_p, llen, *value, width, flags);
557 float *value = (float *)args[arg];
558 AddFloat(&buf_p, llen, *value, width, prec);
564 const char *str = (const char *)args[arg];
565 AddString(&buf_p, llen, str, width, prec);
571 unsigned int *value = (unsigned int *)args[arg];
572 flags |= UPPERDIGITS;
573 AddHex(&buf_p, llen, *value, width, flags);
579 unsigned int *value = (unsigned int *)args[arg];
580 AddHex(&buf_p, llen, *value, width, flags);
620 return (maxlen - llen - 1);
623 size_t atcprintf(char *buffer, size_t maxlen, const char *format, IPluginContext *pCtx, const cell_t *params, int *param)
625 if (!buffer || !maxlen)
631 int args = params[0];
640 size_t llen = maxlen - 1;
648 // run through the format string until we hit a '%' or '\0'
649 for (ch = *fmt; llen && ((ch = *fmt) != '\0') && (ch != '%'); fmt++)
654 if ((ch == '\0') || (llen <= 0))
662 // reset formatting state
681 while(is_digit((ch = *fmt++)))
683 n = 10 * n + (ch - '0');
685 prec = (n < 0) ? -1 : n;
706 n = 10 * n + (ch - '0');
708 } while(is_digit(ch));
720 pCtx->LocalToString(params[arg], &c);
731 pCtx->LocalToPhysAddr(params[arg], &value);
732 AddInt(&buf_p, llen, static_cast<int>(*value), width, flags);
740 pCtx->LocalToPhysAddr(params[arg], &value);
741 AddUInt(&buf_p, llen, static_cast<unsigned int>(*value), width, flags);
749 pCtx->LocalToPhysAddr(params[arg], &value);
750 AddFloat(&buf_p, llen, sp_ctof(*value), width, prec);
758 pCtx->LocalToPhysAddr(params[arg], &value);
762 CPlayer *player = g_Players.GetPlayerByIndex(*value);
763 if (!player || !player->IsConnected())
765 return pCtx->ThrowNativeError("Client index %d is invalid", *value);
767 const char *auth = player->GetAuthString();
768 if (!auth || auth[0] == '\0')
770 auth = "STEAM_ID_PENDING";
772 int userid = engine->GetPlayerUserId(player->GetEdict());
782 "Console<0><Console><Console>");
784 AddString(&buf_p, llen, buffer, width, prec);
793 if ((err=pCtx->LocalToString(params[arg], &str)) != SP_ERROR_NONE)
795 pCtx->ThrowNativeErrorEx(err, "Could not deference string");
798 AddString(&buf_p, llen, str, width, prec);
809 pCtx->LocalToString(params[arg++], &key);
810 pCtx->LocalToPhysAddr(params[arg++], &target);
811 res = Translate(buf_p, llen, pCtx, key, *target, params, &arg, &error);
826 cell_t target = g_SourceMod.GetGlobalTarget();
827 pCtx->LocalToString(params[arg++], &key);
828 res = Translate(buf_p, llen, pCtx, key, target, params, &arg, &error);
841 pCtx->LocalToPhysAddr(params[arg], &value);
842 flags |= UPPERDIGITS;
843 AddHex(&buf_p, llen, static_cast<unsigned int>(*value), width, flags);
851 pCtx->LocalToPhysAddr(params[arg], &value);
852 AddHex(&buf_p, llen, static_cast<unsigned int>(*value), width, flags);
892 return (maxlen - llen - 1);
895 const char *stristr(const char *str, const char *substr)
899 return ((char *)str);
902 char *needle = (char *)substr;
903 char *prevloc = (char *)str;
904 char *haystack = (char *)str;
908 if (tolower(*haystack) == tolower(*needle))
916 haystack = ++prevloc;
917 needle = (char *)substr;
924 unsigned int strncopy(char *dest, const char *src, size_t count)
932 while ((*src) && (--count))
938 return (dest - start);
941 size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...)
945 size_t len = vsnprintf(buffer, maxlength, fmt, ap);
948 if (len >= maxlength)
950 buffer[maxlength - 1] = '\0';
951 return (maxlength - 1);
957 size_t UTIL_FormatArgs(char *buffer, size_t maxlength, const char *fmt, va_list ap)
959 size_t len = vsnprintf(buffer, maxlength, fmt, ap);
961 if (len >= maxlength)
963 buffer[maxlength - 1] = '\0';
964 return (maxlength - 1);
970 char *sm_strdup(const char *str)
972 char *ptr = new char[strlen(str)+1];
977 unsigned int UTIL_ReplaceAll(char *subject, size_t maxlength, const char *search, const char *replace)
979 size_t searchLen = strlen(search);
980 size_t replaceLen = strlen(replace);
983 unsigned int total = 0;
984 while ((ptr = UTIL_ReplaceEx(ptr, maxlength, search, searchLen, replace, replaceLen)) != NULL)
997 * NOTE: Do not edit this for the love of god unless you have
998 * read the test cases and understand the code behind each one.
999 * While I don't guarantee there aren't mistakes, I do guarantee
1000 * that plugins will end up relying on tiny idiosyncracies of this
1001 * function, just like they did with AMX Mod X.
1003 * There are explicitly more cases than the AMX Mod X version because
1004 * we're not doing a blind copy. Each case is specifically optimized
1005 * for what needs to be done. Even better, we don't have to error on
1006 * bad buffer sizes. Instead, this function will smartly cut off the
1007 * string in a way that pushes old data out.
1009 char *UTIL_ReplaceEx(char *subject, size_t maxLen, const char *search, size_t searchLen, const char *replace, size_t replaceLen)
1011 char *ptr = subject;
1013 size_t textLen = strlen(subject);
1015 /* It's not possible to search or replace */
1016 if (searchLen > textLen || maxLen <= 1)
1021 /* Subtract one off the maxlength so we can include the null terminator */
1024 while (*ptr != '\0' && (browsed <= textLen - searchLen))
1026 /* See if we get a comparison */
1027 if (strncmp(ptr, search, searchLen) == 0)
1029 if (replaceLen > searchLen)
1031 /* First, see if we have enough space to do this operation */
1032 if (maxLen - textLen < replaceLen - searchLen)
1034 /* First, see if the replacement length goes out of bounds. */
1035 if (browsed + replaceLen >= maxLen)
1041 * Replace: DDDDDDDDDD
1042 * OUTPUT : AADDDDDDDDD
1045 /* If it does, we'll just bound the length and do a strcpy. */
1046 replaceLen = maxLen - browsed;
1047 /* Note, we add one to the final result for the null terminator */
1048 strncopy(ptr, replace, replaceLen+1);
1055 * OUTPUT : AADDDDDDDCC
1058 /* We're going to have some bytes left over... */
1059 size_t origBytesToCopy = (textLen - (browsed + searchLen)) + 1;
1060 size_t realBytesToCopy = (maxLen - (browsed + replaceLen)) + 1;
1061 char *moveFrom = ptr + searchLen + (origBytesToCopy - realBytesToCopy);
1062 char *moveTo = ptr + replaceLen;
1064 /* First, move our old data out of the way. */
1065 memmove(moveTo, moveFrom, realBytesToCopy);
1067 /* Now, do our replacement. */
1068 memcpy(ptr, replace, replaceLen);
1076 * OUTPUT : AADDDDCCC
1079 /* Yes, we have enough space. Do a normal move operation. */
1080 char *moveFrom = ptr + searchLen;
1081 char *moveTo = ptr + replaceLen;
1083 /* First move our old data out of the way. */
1084 size_t bytesToCopy = (textLen - (browsed + searchLen)) + 1;
1085 memmove(moveTo, moveFrom, bytesToCopy);
1087 /* Now do our replacement. */
1088 memcpy(ptr, replace, replaceLen);
1090 } else if (replaceLen < searchLen) {
1099 /* If the replacement does not grow the string length, we do not
1100 * need to do any fancy checking at all. Yay!
1102 char *moveFrom = ptr + searchLen; /* Start after the search pointer */
1103 char *moveTo = ptr + replaceLen; /* Copy to where the replacement ends */
1105 /* Copy our replacement in, if any */
1108 memcpy(ptr, replace, replaceLen);
1111 /* Figure out how many bytes to move down, including null terminator */
1112 size_t bytesToCopy = (textLen - (browsed + searchLen)) + 1;
1114 /* Move the rest of the string down */
1115 memmove(moveTo, moveFrom, bytesToCopy);
1125 /* We don't have to move anything around, just do a straight copy */
1126 memcpy(ptr, replace, replaceLen);
1129 return ptr + replaceLen;