atcprintf() is now fully re-entrant, meaning translations can be used from inside translations
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.GetClientLanguage(client), &pTrans);
59 if (err != Trans_Okay)
61 err = g_pCorePhrases->GetTranslation(phrase, g_Translator.GetServerLanguage(), &pTrans);
62 if (err != Trans_Okay && g_Translator.GetServerLanguage() != CORELANG_ENGLISH)
64 err = g_pCorePhrases->GetTranslation(phrase, CORELANG_ENGLISH, &pTrans);
68 if (err != Trans_Okay)
70 return UTIL_Format(buffer, maxlength, "%s", phrase);
73 return g_Translator.Translate(buffer, maxlength, params, &pTrans);
76 inline bool TryTranslation(CPlugin *pl, const char *key, unsigned int langid, unsigned int langcount, Translation *pTrans)
78 TransError err = Trans_BadLanguage;
81 for (size_t i=0; i<langcount && err!=Trans_Okay; i++)
83 phrfl = g_Translator.GetFileByIndex(pl->GetLangFileByIndex(i));
84 err = phrfl->GetTranslation(key, langid, pTrans);
87 return (err == Trans_Okay) ? true : false;
90 inline void ReorderTranslationParams(const Translation *pTrans, cell_t *params)
92 cell_t new_params[MAX_TRANSLATE_PARAMS];
93 for (unsigned int i = 0; i < pTrans->fmt_count; i++)
95 new_params[i] = params[pTrans->fmt_order[i]];
97 memcpy(params, new_params, pTrans->fmt_count * sizeof(cell_t));
100 size_t Translate(char *buffer,
102 IPluginContext *pCtx,
105 const cell_t *params,
112 CPlugin *pl = (CPlugin *)g_PluginSys.FindPluginByContext(pCtx->GetContext());
113 size_t langcount = pl->GetLangFileCount();
114 unsigned int max_params = 0;
117 if (target == LANG_SERVER)
119 langid = g_Translator.GetServerLanguage();
121 else if ((target >= 1) && (target <= g_Players.GetMaxClients()))
123 langid = g_Translator.GetClientLanguage(target);
127 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Translation failed: invalid client index %d", target);
131 if (!TryTranslation(pl, key, langid, langcount, &pTrans))
133 if (target != LANG_SERVER && langid != g_Translator.GetServerLanguage())
135 target = LANG_SERVER;
138 else if (langid != LANGUAGE_ENGLISH)
140 if (!TryTranslation(pl, key, LANGUAGE_ENGLISH, langcount, &pTrans))
142 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Language phrase \"%s\" not found", key);
148 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Language phrase \"%s\" not found", key);
153 max_params = pTrans.fmt_count;
157 /* Check if we're going to over the limit */
158 if ((*arg) + (max_params - 1) > (size_t)params[0])
160 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAMS_MAX,
161 "Translation string formatted incorrectly - missing at least %d parameters",
162 ((*arg + (max_params - 1)) - params[0])
167 /* Re-order the parameters that this translation requires */
168 ReorderTranslationParams(&pTrans, const_cast<cell_t *>(¶ms[*arg]));
171 /* Now, call back into atcprintf() which is re-entrant */
172 return atcprintf(buffer, maxlen, pTrans.szPhrase, pCtx, params, arg);
179 void AddString(char **buf_p, size_t &maxlen, const char *string, int width, int prec)
183 static char nlstr[] = {'(','n','u','l','l',')','\0'};
195 for (size = 0; size < prec; size++)
197 if (string[size] == '\0')
203 while (string[size++]);
207 if (size > (int)maxlen)
220 while ((width-- > 0) && maxlen)
229 void AddFloat(char **buf_p, size_t &maxlen, double fval, int width, int prec)
244 // write the float number
249 text[digits++] = '0' + val % 10;
255 text[digits++] = '-';
260 while ((digits < width) && maxlen)
267 while ((digits--) && maxlen)
269 *buf++ = text[digits];
279 // write the fraction
281 while (digits < prec)
286 text[digits++] = '0' + val % 10;
289 if ((digits > 0) && maxlen)
294 for (prec = 0; maxlen && (prec < digits); prec++)
303 void AddUInt(char **buf_p, size_t &maxlen, unsigned int val, int width, int flags)
312 text[digits++] = '0' + val % 10;
318 if (!(flags & LADJUST))
320 while (digits < width && maxlen)
322 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
328 while (digits-- && maxlen)
330 *buf++ = text[digits];
337 while (width-- && maxlen)
339 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
347 void AddInt(char **buf_p, size_t &maxlen, int val, int width, int flags)
353 unsigned int unsignedVal;
359 /* we want the unsigned version */
360 unsignedVal = abs(val);
366 text[digits++] = '0' + unsignedVal % 10;
368 } while (unsignedVal);
372 text[digits++] = '-';
377 if (!(flags & LADJUST))
379 while ((digits < width) && maxlen)
381 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
387 while (digits-- && maxlen)
389 *buf++ = text[digits];
396 while (width-- && maxlen)
398 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
406 void AddHex(char **buf_p, size_t &maxlen, unsigned int val, int width, int flags)
414 if (flags & UPPERDIGITS)
416 hexadjust = 'A' - '9' - 1;
418 hexadjust = 'a' - '9' - 1;
424 digit = ('0' + val % 16);
430 text[digits++] = digit;
436 if (!(flags & LADJUST))
438 while (digits < width && maxlen)
440 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
446 while (digits-- && maxlen)
448 *buf++ = text[digits];
455 while (width-- && maxlen)
457 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
465 size_t gnprintf(char *buffer, size_t maxlen, const char *format, void **args)
467 if (!buffer || !maxlen)
481 size_t llen = maxlen - 1;
488 // run through the format string until we hit a '%' or '\0'
489 for (ch = *fmt; llen && ((ch = *fmt) != '\0') && (ch != '%'); fmt++)
494 if ((ch == '\0') || (llen <= 0))
502 // reset formatting state
521 while(is_digit((ch = *fmt++)))
523 n = 10 * n + (ch - '0');
525 prec = (n < 0) ? -1 : n;
546 n = 10 * n + (ch - '0');
548 } while(is_digit(ch));
558 char *c = (char *)args[arg];
567 int *value = (int *)args[arg];
568 AddInt(&buf_p, llen, *value, width, flags);
574 unsigned int *value = (unsigned int *)args[arg];
575 AddUInt(&buf_p, llen, *value, width, flags);
581 float *value = (float *)args[arg];
582 AddFloat(&buf_p, llen, *value, width, prec);
588 const char *str = (const char *)args[arg];
589 AddString(&buf_p, llen, str, width, prec);
595 unsigned int *value = (unsigned int *)args[arg];
596 flags |= UPPERDIGITS;
597 AddHex(&buf_p, llen, *value, width, flags);
603 unsigned int *value = (unsigned int *)args[arg];
604 AddHex(&buf_p, llen, *value, width, flags);
644 return (maxlen - llen - 1);
647 size_t atcprintf(char *buffer, size_t maxlen, const char *format, IPluginContext *pCtx, const cell_t *params, int *param)
649 if (!buffer || !maxlen)
655 int args = params[0];
664 size_t llen = maxlen - 1;
672 // run through the format string until we hit a '%' or '\0'
673 for (ch = *fmt; llen && ((ch = *fmt) != '\0') && (ch != '%'); fmt++)
678 if ((ch == '\0') || (llen <= 0))
686 // reset formatting state
705 while(is_digit((ch = *fmt++)))
707 n = 10 * n + (ch - '0');
709 prec = (n < 0) ? -1 : n;
730 n = 10 * n + (ch - '0');
732 } while(is_digit(ch));
744 pCtx->LocalToString(params[arg], &c);
755 pCtx->LocalToPhysAddr(params[arg], &value);
756 AddInt(&buf_p, llen, static_cast<int>(*value), width, flags);
764 pCtx->LocalToPhysAddr(params[arg], &value);
765 AddUInt(&buf_p, llen, static_cast<unsigned int>(*value), width, flags);
773 pCtx->LocalToPhysAddr(params[arg], &value);
774 AddFloat(&buf_p, llen, sp_ctof(*value), width, prec);
782 pCtx->LocalToPhysAddr(params[arg], &value);
786 CPlayer *player = g_Players.GetPlayerByIndex(*value);
787 if (!player || !player->IsConnected())
789 return pCtx->ThrowNativeError("Client index %d is invalid", *value);
791 const char *auth = player->GetAuthString();
792 if (!auth || auth[0] == '\0')
794 auth = "STEAM_ID_PENDING";
796 int userid = engine->GetPlayerUserId(player->GetEdict());
806 "Console<0><Console><Console>");
808 AddString(&buf_p, llen, buffer, width, prec);
816 pCtx->LocalToPhysAddr(params[arg], &value);
818 const char *name = "Console";
821 CPlayer *player = g_Players.GetPlayerByIndex(*value);
822 if (!player || !player->IsConnected())
824 return pCtx->ThrowNativeError("Client index %d is invalid", *value);
826 name = player->GetName();
828 AddString(&buf_p, llen, name, width, prec);
837 if ((err=pCtx->LocalToString(params[arg], &str)) != SP_ERROR_NONE)
839 pCtx->ThrowNativeErrorEx(err, "Could not deference string");
842 AddString(&buf_p, llen, str, width, prec);
853 pCtx->LocalToString(params[arg++], &key);
854 pCtx->LocalToPhysAddr(params[arg++], &target);
855 res = Translate(buf_p, llen, pCtx, key, *target, params, &arg, &error);
870 cell_t target = g_SourceMod.GetGlobalTarget();
871 pCtx->LocalToString(params[arg++], &key);
872 res = Translate(buf_p, llen, pCtx, key, target, params, &arg, &error);
885 pCtx->LocalToPhysAddr(params[arg], &value);
886 flags |= UPPERDIGITS;
887 AddHex(&buf_p, llen, static_cast<unsigned int>(*value), width, flags);
895 pCtx->LocalToPhysAddr(params[arg], &value);
896 AddHex(&buf_p, llen, static_cast<unsigned int>(*value), width, flags);
936 return (maxlen - llen - 1);
939 const char *stristr(const char *str, const char *substr)
943 return ((char *)str);
946 char *needle = (char *)substr;
947 char *prevloc = (char *)str;
948 char *haystack = (char *)str;
952 if (tolower(*haystack) == tolower(*needle))
960 haystack = ++prevloc;
961 needle = (char *)substr;
968 unsigned int strncopy(char *dest, const char *src, size_t count)
976 while ((*src) && (--count))
982 return (dest - start);
985 size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...)
989 size_t len = vsnprintf(buffer, maxlength, fmt, ap);
992 if (len >= maxlength)
994 buffer[maxlength - 1] = '\0';
995 return (maxlength - 1);
1001 size_t UTIL_FormatArgs(char *buffer, size_t maxlength, const char *fmt, va_list ap)
1003 size_t len = vsnprintf(buffer, maxlength, fmt, ap);
1005 if (len >= maxlength)
1007 buffer[maxlength - 1] = '\0';
1008 return (maxlength - 1);
1014 char *sm_strdup(const char *str)
1016 char *ptr = new char[strlen(str)+1];
1021 unsigned int UTIL_ReplaceAll(char *subject, size_t maxlength, const char *search, const char *replace)
1023 size_t searchLen = strlen(search);
1024 size_t replaceLen = strlen(replace);
1026 char *ptr = subject;
1027 unsigned int total = 0;
1028 while ((ptr = UTIL_ReplaceEx(ptr, maxlength, search, searchLen, replace, replaceLen)) != NULL)
1041 * NOTE: Do not edit this for the love of god unless you have
1042 * read the test cases and understand the code behind each one.
1043 * While I don't guarantee there aren't mistakes, I do guarantee
1044 * that plugins will end up relying on tiny idiosyncracies of this
1045 * function, just like they did with AMX Mod X.
1047 * There are explicitly more cases than the AMX Mod X version because
1048 * we're not doing a blind copy. Each case is specifically optimized
1049 * for what needs to be done. Even better, we don't have to error on
1050 * bad buffer sizes. Instead, this function will smartly cut off the
1051 * string in a way that pushes old data out.
1053 char *UTIL_ReplaceEx(char *subject, size_t maxLen, const char *search, size_t searchLen, const char *replace, size_t replaceLen)
1055 char *ptr = subject;
1057 size_t textLen = strlen(subject);
1059 /* It's not possible to search or replace */
1060 if (searchLen > textLen)
1065 /* Handle the case of one byte replacement.
1066 * It's only valid in one case.
1070 /* If the search matches and the replace length is 0,
1071 * we can just terminate the string and be done.
1073 if (strcmp(subject, search) == 0 && replaceLen == 0)
1084 /* Subtract one off the maxlength so we can include the null terminator */
1087 while (*ptr != '\0' && (browsed <= textLen - searchLen))
1089 /* See if we get a comparison */
1090 if (strncmp(ptr, search, searchLen) == 0)
1092 if (replaceLen > searchLen)
1094 /* First, see if we have enough space to do this operation */
1095 if (maxLen - textLen < replaceLen - searchLen)
1097 /* First, see if the replacement length goes out of bounds. */
1098 if (browsed + replaceLen >= maxLen)
1104 * Replace: DDDDDDDDDD
1105 * OUTPUT : AADDDDDDDDD
1108 /* If it does, we'll just bound the length and do a strcpy. */
1109 replaceLen = maxLen - browsed;
1110 /* Note, we add one to the final result for the null terminator */
1111 strncopy(ptr, replace, replaceLen+1);
1118 * OUTPUT : AADDDDDDDCC
1121 /* We're going to have some bytes left over... */
1122 size_t origBytesToCopy = (textLen - (browsed + searchLen)) + 1;
1123 size_t realBytesToCopy = (maxLen - (browsed + replaceLen)) + 1;
1124 char *moveFrom = ptr + searchLen + (origBytesToCopy - realBytesToCopy);
1125 char *moveTo = ptr + replaceLen;
1127 /* First, move our old data out of the way. */
1128 memmove(moveTo, moveFrom, realBytesToCopy);
1130 /* Now, do our replacement. */
1131 memcpy(ptr, replace, replaceLen);
1139 * OUTPUT : AADDDDCCC
1142 /* Yes, we have enough space. Do a normal move operation. */
1143 char *moveFrom = ptr + searchLen;
1144 char *moveTo = ptr + replaceLen;
1146 /* First move our old data out of the way. */
1147 size_t bytesToCopy = (textLen - (browsed + searchLen)) + 1;
1148 memmove(moveTo, moveFrom, bytesToCopy);
1150 /* Now do our replacement. */
1151 memcpy(ptr, replace, replaceLen);
1153 } else if (replaceLen < searchLen) {
1162 /* If the replacement does not grow the string length, we do not
1163 * need to do any fancy checking at all. Yay!
1165 char *moveFrom = ptr + searchLen; /* Start after the search pointer */
1166 char *moveTo = ptr + replaceLen; /* Copy to where the replacement ends */
1168 /* Copy our replacement in, if any */
1171 memcpy(ptr, replace, replaceLen);
1174 /* Figure out how many bytes to move down, including null terminator */
1175 size_t bytesToCopy = (textLen - (browsed + searchLen)) + 1;
1177 /* Move the rest of the string down */
1178 memmove(moveTo, moveFrom, bytesToCopy);
1188 /* We don't have to move anything around, just do a straight copy */
1189 memcpy(ptr, replace, replaceLen);
1192 return ptr + replaceLen;