Annotation of parser3/src/classes/string.C, revision 1.253

1.24      paf         1: /** @file
                      2:        Parser: @b string parser class.
                      3: 
1.251     moko        4:        Copyright (c) 2001-2023 Art. Lebedev Studio (http://www.artlebedev.com)
                      5:        Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>
1.113     paf         6: */
1.24      paf         7: 
1.43      paf         8: #include "classes.h"
1.126     paf         9: #include "pa_vmethod_frame.h"
1.241     moko       10: #include "pa_base64.h"
1.126     paf        11: 
1.1       paf        12: #include "pa_request.h"
                     13: #include "pa_vdouble.h"
                     14: #include "pa_vint.h"
1.17      paf        15: #include "pa_vtable.h"
1.25      paf        16: #include "pa_vbool.h"
1.27      paf        17: #include "pa_string.h"
1.53      parser     18: #include "pa_sql_connection.h"
1.71      parser     19: #include "pa_dictionary.h"
1.119     paf        20: #include "pa_vmethod_frame.h"
1.174     misha      21: #include "pa_vregex.h"
1.189     misha      22: #include "pa_charsets.h"
1.1       paf        23: 
1.253   ! moko       24: volatile const char * IDENT_STRING_C="$Id: string.C,v 1.252 2024/09/07 15:01:38 moko Exp $";
1.203     moko       25: 
1.41      paf        26: // class
                     27: 
1.126     paf        28: class MString: public Methoded {
1.41      paf        29: public:
1.126     paf        30:        MString();
1.41      paf        31: };
1.1       paf        32: 
1.126     paf        33: // global variable
                     34: 
1.224     moko       35: DECLARE_CLASS_VAR(string, new MString);
1.126     paf        36: 
1.196     moko       37: // void class, inherited from string and thus should be inited afterwards
                     38: 
                     39: class MVoid: public Methoded {
                     40: public:
                     41:        MVoid();
                     42: };
                     43: 
                     44: // void global variable should be after string global variable
                     45: 
1.224     moko       46: DECLARE_CLASS_VAR(void, new MVoid);
1.196     moko       47: 
1.126     paf        48: // defines for statics
                     49: 
                     50: #define MATCH_VAR_NAME "match"
1.162     misha      51: #define TRIM_START_OPTION "left"
                     52: #define TRIM_END_OPTION "right"
1.133     paf        53: #define TRIM_BOTH_OPTION "both"
1.126     paf        54: 
1.189     misha      55: #define MODE_APPEND "append"
                     56: 
1.220     moko       57: #define UNESCAPE_MODE_JS "js"
                     58: #define UNESCAPE_MODE_URI "uri"
                     59: 
1.126     paf        60: // statics
                     61: 
                     62: static const String match_var_name(MATCH_VAR_NAME);
                     63: 
1.1       paf        64: // methods
                     65: 
1.126     paf        66: static void _length(Request& r, MethodParams&) {
1.163     misha      67:        double result=GET_SELF(r, VString).string().length(r.charsets.source());
1.233     moko       68:        r.write(*new VDouble(result));
1.1       paf        69: }
                     70: 
1.126     paf        71: static void _int(Request& r, MethodParams& params) {
                     72:        const String& self_string=GET_SELF(r, VString).string();
1.72      parser     73:        int converted;
1.206     moko       74: 
                     75:        if(self_string.is_empty()) {
1.144     paf        76:                if(params.count()>0)
                     77:                        converted=params.as_int(0, "default must be int", r); // (default)
1.84      parser     78:                else
1.206     moko       79:                        throw Exception(PARSER_RUNTIME, 0, "unable to convert empty string without default specified");
                     80:        } else {
                     81:                try {
                     82:                        converted=self_string.as_int();
                     83:                } catch(...) { // convert problem
                     84:                        if(params.count()>0)
                     85:                                converted=params.as_int(0, "default must be int", r); // (default)
                     86:                        else
                     87:                                rethrow; // we have a problem when no default
                     88:                }
1.72      parser     89:        }
1.206     moko       90: 
1.233     moko       91:        r.write(*new VInt(converted));
1.1       paf        92: }
                     93: 
1.126     paf        94: static void _double(Request& r, MethodParams& params) {
                     95:        const String& self_string=GET_SELF(r, VString).string();
1.206     moko       96: 
                     97:        if(self_string.is_empty()) {
1.144     paf        98:                if(params.count()>0)
1.233     moko       99:                        r.write(*new VDouble(params.as_double(0, "default must be double", r))); // (default)
1.84      parser    100:                else
1.206     moko      101:                        throw Exception(PARSER_RUNTIME, 0, "unable to convert empty string without default specified");
                    102:        } else {
                    103:                try {
1.233     moko      104:                        r.write(*new VDouble(self_string.as_double()));
1.206     moko      105:                } catch(...) { // convert problem
                    106:                        if(params.count()>0)
1.233     moko      107:                                r.write(*new VDouble(params.as_double(0, "default must be double", r))); // (default)
1.206     moko      108:                        else
                    109:                                rethrow; // we have a problem when no default
                    110:                }
1.72      parser    111:        }
1.1       paf       112: }
                    113: 
1.151     misha     114: static void _bool(Request& r, MethodParams& params) {
                    115:        const String& self_string=GET_SELF(r, VString).string();
                    116:        bool converted;
1.206     moko      117:        const char *str=self_string.cstr();
                    118: 
                    119:        if(self_string.is_empty()) {
                    120:                if(params.count()>0)
                    121:                        converted=params.as_bool(0, "default must be bool", r); // (default)
                    122:                else
                    123:                        throw Exception(PARSER_RUNTIME, 0, "unable to convert empty string without default specified");
1.207     moko      124:        } else if( (str[0]=='T' || str[0]=='t') && (str[1]=='R' || str[1]=='r') && (str[2]=='U' || str[2]=='u') &&
1.206     moko      125:                   (str[3]=='E' || str[3]=='e') && str[4]==0 ) { // "true"
                    126:                converted=true;
1.207     moko      127:        } else if( (str[0]=='F' || str[0]=='f') && (str[1]=='A' || str[1]=='a') && (str[2]=='L' || str[2]=='l') &&
1.206     moko      128:                   (str[3]=='S' || str[3]=='s') && (str[4]=='E' || str[4]=='e') && str[5]==0 ) { // "false"
                    129:                converted=false;
                    130:        } else {
1.158     misha     131:                try {
                    132:                        converted=self_string.as_bool();
1.206     moko      133:                } catch(...) { // convert problem
                    134:                        if(params.count()>0)
                    135:                                converted=params.as_bool(0, "default must be bool", r); // (default)
                    136:                        else
                    137:                                rethrow; // we have a problem when no default
1.158     misha     138:                }
1.151     misha     139:        }
                    140: 
1.233     moko      141:        r.write(VBool::get(converted));
1.151     misha     142: }
                    143: 
1.126     paf       144: /*not static*/void _string_format(Request& r, MethodParams& params) {
1.9       paf       145: 
1.126     paf       146:        Value& fmt_maybe_code=params[0];
1.95      paf       147:        // for some time due to stupid {} in original design
1.99      paf       148:        const String& fmt=r.process_to_string(fmt_maybe_code);
1.9       paf       149: 
1.159     misha     150:        const char* buf=format(r.get_self().as_double(), fmt.trim().cstrm());
1.63      parser    151: 
1.233     moko      152:        r.write(String(buf));
1.9       paf       153: }
1.11      paf       154: 
1.126     paf       155: static void _left(Request& r, MethodParams& params) {
1.244     moko      156:        int sn=params.as_int(0, "n must be int", r);
1.126     paf       157:        const String& string=GET_SELF(r, VString).string();
1.244     moko      158:        r.write(sn<0 ? string : string.mid(r.charsets.source(), 0, sn));
1.15      paf       159: }
                    160: 
1.126     paf       161: static void _right(Request& r, MethodParams& params) {
1.244     moko      162:        int sn=params.as_int(0, "n must be int", r);
1.216     moko      163:        if(sn>0){
1.244     moko      164:                size_t n=sn;
1.216     moko      165:                const String& string=GET_SELF(r, VString).string();
                    166:                size_t length=string.length(r.charsets.source());
1.233     moko      167:                r.write(n<length ? string.mid(r.charsets.source(), length-n, length, length) : string);
1.216     moko      168:        }
1.15      paf       169: }
                    170: 
1.126     paf       171: static void _mid(Request& r, MethodParams& params) {
                    172:        const String& string=GET_SELF(r, VString).string();
1.83      parser    173: 
1.245     moko      174:        int begin=params.as_int(0, "p must be int", r);
                    175:        if(begin<0)
                    176:                throw Exception(PARSER_RUNTIME, 0,  "p(%d) must be >=0", begin);
1.138     paf       177: 
                    178:        size_t end;
1.164     misha     179:        size_t length=0;
1.245     moko      180: 
1.138     paf       181:        if(params.count()>1) {
1.245     moko      182:                int n=params.as_int(1, "n must be int", r);
                    183:                if(n<0)
                    184:                        throw Exception(PARSER_RUNTIME, 0, "n(%d) must be >=0", n);
                    185:                end=begin+n;
1.164     misha     186:        } else {
                    187:                length=string.length(r.charsets.source());
                    188:                end=length;
                    189:        }
1.163     misha     190: 
1.233     moko      191:        r.write(string.mid(r.charsets.source(), begin, end, length));
1.15      paf       192: }
                    193: 
1.126     paf       194: static void _pos(Request& r, MethodParams& params) {
                    195:        Value& substr=params.as_no_junction(0, "substr must not be code");
1.16      paf       196:        
1.126     paf       197:        const String& string=GET_SELF(r, VString).string();
1.245     moko      198:        int offset=0;
1.165     misha     199:        if(params.count()>1){
                    200:                offset=params.as_int(1, "n must be int", r);
                    201:                if(offset<0)
1.227     moko      202:                        throw Exception(PARSER_RUNTIME, 0, "n(%d) must be >=0", offset);
1.165     misha     203:        }
                    204: 
1.245     moko      205:        r.write(*new VInt((int)string.pos(r.charsets.source(), substr.as_string(), offset)));
1.16      paf       206: }
                    207: 
1.250     moko      208: struct Split_action_info {
                    209:        const String& src;
                    210:        ArrayString &result;
                    211: };
                    212: 
                    213: static void split_action(Table& , ArrayString* row, int prestart, int prefinish, int poststart, int postfinish, void *info) {
                    214:        Split_action_info& ai=*static_cast<Split_action_info *>(info);
                    215:        if(row) { // begin&middle
                    216:                // piece from last match['prestart'] to beginning of this match['prefinish']
                    217:                ai.result += &ai.src.mid(prestart, prefinish);
                    218:        } else // end
                    219:                if(poststart != postfinish)
                    220:                        ai.result += &ai.src.mid(poststart, postfinish);
                    221: }
                    222: 
1.249     moko      223: static void split_list(Value& delim_value, const String& string, ArrayString& result) {
1.250     moko      224:        if(Value* value=delim_value.as(VREGEX_TYPE)){
                    225:                VRegex *vregex=static_cast<VRegex*>(value);
                    226:                vregex->study();
                    227: 
                    228:                int matches_count=0;
                    229:                Split_action_info ai = { string, result };
                    230: 
                    231:                string.match(vregex, split_action, &ai, matches_count);
                    232:        } else
                    233:                string.split(result, 0, delim_value.as_string());
1.19      paf       234: }
                    235: 
1.118     paf       236: #define SPLIT_LEFT 0x0001
                    237: #define SPLIT_RIGHT 0x0010
                    238: #define SPLIT_HORIZONTAL 0x0100
                    239: #define SPLIT_VERTICAL 0x1000
                    240: 
1.126     paf       241: static int split_options(const String* options) {
1.118     paf       242:     struct Split_option {
1.126     paf       243:                const char* keyL;
                    244:                const char* keyU;
1.118     paf       245:                int setBit;
                    246:                int checkBit;
                    247:     } split_option[]={
                    248:                {"l", "L", SPLIT_LEFT, SPLIT_RIGHT}, // 0xVHRL
                    249:                {"r", "R", SPLIT_RIGHT, SPLIT_LEFT},
                    250:                {"h", "H", SPLIT_HORIZONTAL, SPLIT_VERTICAL},
                    251:                {"v", "V", SPLIT_VERTICAL, SPLIT_HORIZONTAL},
1.130     paf       252:                {0, 0, 0, 0}
1.118     paf       253:     };
                    254: 
                    255:        int result=0;
1.126     paf       256:        if(options) {
1.118     paf       257:                for(Split_option *o=split_option; o->keyL; o++) 
1.126     paf       258:                        if(options->pos(o->keyL)!=STRING_NOT_FOUND 
                    259:                                || (o->keyU && options->pos(o->keyU)!=STRING_NOT_FOUND)) {
1.118     paf       260:                                if(result & o->checkBit)
1.238     moko      261:                                        throw Exception(PARSER_RUNTIME, options, "conflicting split options");
1.118     paf       262:                                result |= o->setBit;
                    263:                        }
                    264:        }
                    265: 
                    266:        return result;
                    267: }
                    268: 
1.156     misha     269: static Table& split_vertical(ArrayString& pieces, bool right, const String* column_name) {
1.126     paf       270:        Table::columns_type columns(new ArrayString);
1.156     misha     271:        *columns+=column_name;
1.19      paf       272: 
1.126     paf       273:        Table& table=*new Table(columns, pieces.count());
1.118     paf       274:        if(right) { // right
1.126     paf       275:                for(int i=pieces.count(); --i>=0; ) {
                    276:                        Table::element_type row(new ArrayString);
                    277:                        *row+=pieces[i];
                    278:                        table+=row;
1.118     paf       279:                }
                    280:        } else { // left
1.253   ! moko      281:                for(ArrayString::Iterator i(pieces); i; ) {
1.126     paf       282:                        Table::element_type row(new ArrayString);
                    283:                        *row+=i.next();
                    284:                        table+=row;
1.118     paf       285:                }
1.61      parser    286:        }
1.118     paf       287: 
1.126     paf       288:        return table;
1.19      paf       289: }
                    290: 
1.128     paf       291: static Table& split_horizontal(ArrayString& pieces, bool right) {
1.126     paf       292:        Table& table=*new Table(Table::columns_type(0) /* nameless */);
                    293:        Table::element_type row(new ArrayString(pieces.count()));
1.118     paf       294:        if(right) { // right
1.131     paf       295:                for(int i=pieces.count(); --i>=0; )
1.126     paf       296:                        *row+=pieces[i];
1.118     paf       297:        } else { // left
1.253   ! moko      298:                for(ArrayString::Iterator i(pieces); i; )
1.126     paf       299:                        *row+=i.next();
1.118     paf       300:        }
1.126     paf       301:        table+=row;
1.118     paf       302: 
1.126     paf       303:        return table;
1.118     paf       304: }
                    305: 
1.238     moko      306: static void split_with_options(Request& r, MethodParams& params, int bits) {
1.126     paf       307:        const String& string=GET_SELF(r, VString).string();
1.176     misha     308:        size_t params_count=params.count();
1.19      paf       309: 
1.126     paf       310:        ArrayString pieces;
1.249     moko      311:        split_list(params.as_no_junction(0, "delimiter must not be code"), string, pieces);
1.19      paf       312: 
1.118     paf       313:        if(!bits) {
1.126     paf       314:                const String* options=0;
1.176     misha     315:                if(params_count>1)
1.187     misha     316:                        options=&params.as_string(1, OPTIONS_MUST_NOT_BE_CODE);
1.118     paf       317:                bits=split_options(options);
                    318:        }
1.21      paf       319: 
1.118     paf       320:        bool right=(bits & SPLIT_RIGHT) != 0;
                    321:        bool horizontal=(bits & SPLIT_HORIZONTAL) !=0;
1.156     misha     322: 
                    323:        const String* column_name=0;
1.176     misha     324:        if(params_count>2){
1.156     misha     325:                column_name=&params.as_string(2, COLUMN_NAME_MUST_BE_STRING);
1.178     misha     326:                if (horizontal && !column_name->is_empty()) 
1.238     moko      327:                        throw Exception(PARSER_RUNTIME, column_name, "column name can't be specified with horisontal split");
1.156     misha     328:        } 
1.178     misha     329:        if(!column_name || column_name->is_empty())
1.156     misha     330:                column_name=new String("piece");
                    331: 
                    332:        Table& table=horizontal?split_horizontal(pieces, right):split_vertical(pieces, right, column_name);
1.17      paf       333: 
1.233     moko      334:        r.write(*new VTable(&table));
1.118     paf       335: }
1.126     paf       336: static void _split(Request& r, MethodParams& params) {
                    337:        split_with_options(r, params, 0 /* maybe-determine from param #2 */);
1.118     paf       338: }
1.126     paf       339: static void _lsplit(Request& r, MethodParams& params) {
                    340:        split_with_options(r, params, SPLIT_LEFT);
1.118     paf       341: }
1.126     paf       342: static void _rsplit(Request& r, MethodParams& params) {
                    343:        split_with_options(r, params, SPLIT_RIGHT);
1.17      paf       344: }
                    345: 
1.126     paf       346: static void search_action(Table& table, Table::element_type row, int, int, int, int, void *) {
1.28      paf       347:        if(row)
                    348:                table+=row;
1.27      paf       349: }
                    350: 
1.74      parser    351: #ifndef DOXYGEN
1.27      paf       352: struct Replace_action_info {
1.181     misha     353:        Request* request;
                    354:        const String* src;
                    355:        String* dest;
1.126     paf       356:        VTable* vtable;
                    357:        Value* replacement_code;
1.27      paf       358: };
1.74      parser    359: #endif
1.105     paf       360: /// @todo they can do $global[$result] there, getting pointer to later-invalid local var, kill this
1.238     moko      361: static void replace_action(Table& table, ArrayString* row, int prestart, int prefinish, int poststart, int postfinish, void *info) {
1.27      paf       362:        Replace_action_info& ai=*static_cast<Replace_action_info *>(info);
1.31      paf       363:        if(row) { // begin&middle
1.104     paf       364:                // piece from last match['prestart'] to beginning of this match['prefinish']
                    365:                if(prestart!=prefinish)
                    366:                        *ai.dest << ai.src->mid(prestart, prefinish);//ai.dest->APPEND_CONST("-");
1.51      parser    367:                // store found parts in one-record VTable
1.126     paf       368:                if(table.count()) // middle
1.32      paf       369:                        table.put(0, row);
                    370:                else // begin
1.30      paf       371:                        table+=row;
1.181     misha     372: 
1.30      paf       373:                { // execute 'replacement_code' in 'table' context
1.181     misha     374:                        if(ai.replacement_code){
                    375:                                ai.vtable->set_table(table);
                    376:                                *ai.dest << ai.request->process_to_string(*ai.replacement_code);
                    377:                        }
1.29      paf       378:                }
                    379:        } else // end
1.104     paf       380:                *ai.dest << ai.src->mid(poststart, postfinish);
1.27      paf       381: }
                    382: 
1.126     paf       383: static void _match(Request& r, MethodParams& params) {
1.174     misha     384:        size_t params_count=params.count();
                    385: 
1.126     paf       386:        Value& regexp=params.as_no_junction(0, "regexp must not be code");
1.187     misha     387:        Value* options=(params_count>1)?&params.as_no_junction(1, OPTIONS_MUST_NOT_BE_CODE):0;
1.174     misha     388: 
                    389:        VRegex* vregex;
                    390:        VRegexCleaner vrcleaner;
1.126     paf       391: 
1.188     misha     392:        if(Value* value=regexp.as(VREGEX_TYPE)){
1.174     misha     393:                if(options && options->is_defined())
1.237     moko      394:                        throw Exception(PARSER_RUNTIME, 0, "you can not specify regex-object and options together");
1.174     misha     395:                vregex=static_cast<VRegex*>(value);
                    396:        } else {
1.237     moko      397:                vregex=new VRegex(r.charsets.source(), &regexp.as_string(), (options) ? (&options->as_string()) : 0);
1.175     misha     398:                vregex->study();
1.174     misha     399:                vrcleaner.vregex=vregex;
                    400:        }
1.126     paf       401: 
                    402:        const String& src=GET_SELF(r, VString).string();
1.152     misha     403:        int matches_count=0;
1.174     misha     404: 
                    405:        if(params_count<3) { // search
1.237     moko      406:                Table* table=src.match(vregex, search_action, 0, matches_count);
1.174     misha     407: 
1.152     misha     408:                if(table){
1.233     moko      409:                        r.write(*new VTable(table));
1.152     misha     410:                } else {
1.233     moko      411:                        r.write(*new VInt(matches_count));
1.152     misha     412:                }
                    413: 
1.27      paf       414:        } else { // replace
1.181     misha     415: 
                    416:                Value* replacement_code=0;
                    417:                bool is_junction=false;
                    418: 
                    419:                Value* replacement=&params[2];
                    420:                if(replacement->get_junction()){
                    421:                        replacement_code=replacement;
                    422:                        is_junction=true;
                    423:                } else if(replacement->is_string()){
                    424:                        if(replacement->is_defined())
                    425:                                replacement_code=replacement;
                    426:                } else if(!replacement->is_void())
1.238     moko      427:                        throw Exception(PARSER_RUNTIME, 0, "replacement option should be junction or string");
1.106     paf       428: 
1.238     moko      429:                Value* default_code=(params_count==4) ? &params.as_junction(3, "default value must be code") : 0;
1.192     misha     430: 
1.126     paf       431:                String result;
                    432:                VTable* vtable=new VTable;
1.130     paf       433:                Replace_action_info info={
                    434:                        &r,
                    435:                        &src,
                    436:                        &result,
                    437:                        vtable,
1.181     misha     438:                        replacement_code
1.130     paf       439:                };
1.181     misha     440: 
1.191     misha     441:                if(is_junction){
1.211     moko      442:                        Temp_value_element temp(r, *replacement_code->get_junction()->method_frame, match_var_name, vtable);
1.191     misha     443:                        src.match(vregex, replace_action, &info, matches_count);
                    444:                } else {
                    445:                        src.match(vregex, replace_action, &info, matches_count);
                    446:                }
1.181     misha     447: 
1.192     misha     448:                if(!matches_count && default_code)
                    449:                        r.process_write(*default_code);
                    450:                else
1.233     moko      451:                        r.write(result);
1.27      paf       452:        }
1.24      paf       453: }
                    454: 
1.238     moko      455: static void change_case(Request& r, MethodParams&, String::Change_case_kind kind) {
1.126     paf       456:        const String& src=GET_SELF(r, VString).string();
1.49      parser    457: 
1.233     moko      458:        r.write(src.change_case(r.charsets.source(), kind));
1.49      parser    459: }
1.126     paf       460: static void _upper(Request& r, MethodParams& params) {
                    461:        change_case(r, params, String::CC_UPPER);
1.49      parser    462: }
1.126     paf       463: static void _lower(Request& r, MethodParams& params) {
                    464:        change_case(r, params, String::CC_LOWER);
1.49      parser    465: }
                    466: 
1.65      parser    467: #ifndef DOXYGEN
1.126     paf       468: class String_sql_event_handlers: public SQL_Driver_query_event_handlers {
                    469:        bool got_column;
1.65      parser    470: public:
1.126     paf       471:        bool got_cell;
1.208     moko      472:        const String* result;
1.126     paf       473: public:
1.240     moko      474:        String_sql_event_handlers():
1.126     paf       475:                got_column(false),
                    476:                got_cell(false),
1.208     moko      477:                result(&String::Empty) {}
1.65      parser    478: 
1.128     paf       479:        bool add_column(SQL_Error& error, const char* /*str*/, size_t /*length*/) {
1.124     paf       480:                if(got_column) {
1.240     moko      481:                        error=SQL_Error("result must contain exactly one column");
1.124     paf       482:                        return true;
                    483:                }
1.65      parser    484:                got_column=true;
1.124     paf       485:                return false;
1.65      parser    486:        }
1.124     paf       487:        bool before_rows(SQL_Error& /*error*/ ) { /* ignore */ return false; }
                    488:        bool add_row(SQL_Error& /*error*/) { /* ignore */ return false; }
1.210     moko      489:        bool add_row_cell(SQL_Error& error, const char* str, size_t) {
1.124     paf       490:                if(got_cell) {
1.240     moko      491:                        error=SQL_Error("result must not contain more then one row");
1.124     paf       492:                        return true;
                    493:                }
                    494:                try {
                    495:                        got_cell=true;
1.208     moko      496:                        result=new String(str, String::L_TAINTED /* no length as 0x00 can be inside */ );
1.124     paf       497:                        return false;
                    498:                } catch(...) {
1.235     moko      499:                        error=SQL_Error("exception occurred in String_sql_event_handlers::add_row_cell");
1.124     paf       500:                        return true;
                    501:                }
1.65      parser    502:        }
                    503: };
                    504: #endif
1.239     moko      505: 
1.141     paf       506: extern int marshal_binds(HashStringValue& hash, SQL_Driver::Placeholder*& placeholders);
                    507: extern void unmarshal_bind_updates(HashStringValue& hash, int placeholder_count, SQL_Driver::Placeholder* placeholders);
                    508: 
1.204     moko      509: const String* sql_result_string(Request& r, MethodParams& params, Value*& default_code) {
1.126     paf       510:        Value& statement=params.as_junction(0, "statement must be code");
1.53      parser    511: 
1.141     paf       512:        HashStringValue* bind=0;
1.160     misha     513:        ulong limit=SQL_NO_LIMIT;
1.70      parser    514:        ulong offset=0;
1.81      parser    515:        default_code=0;
1.199     misha     516:        if(params.count()>1)
1.205     misha     517:                if(HashStringValue* options=params.as_hash(1, "sql options")) {
1.199     misha     518:                        int valid_options=0;
                    519:                        if(Value* vbind=options->get(sql_bind_name)) {
                    520:                                valid_options++;
                    521:                                bind=vbind->get_hash();
                    522:                        }
                    523:                        if(Value* vlimit=options->get(sql_limit_name)) {
                    524:                                valid_options++;
1.230     moko      525:                                limit=(ulong)r.process(*vlimit).as_double();
1.199     misha     526:                        }
                    527:                        if(Value* voffset=options->get(sql_offset_name)) {
                    528:                                valid_options++;
1.230     moko      529:                                offset=(ulong)r.process(*voffset).as_double();
1.199     misha     530:                        }
                    531:                        if((default_code=options->get(sql_default_name))) {
                    532:                                valid_options++;
                    533:                        }
                    534:                        if(valid_options!=options->count())
                    535:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.200     misha     536:                }
1.70      parser    537: 
1.141     paf       538:        SQL_Driver::Placeholder* placeholders=0;
                    539:        uint placeholders_count=0;
                    540:        if(bind)
                    541:                placeholders_count=marshal_binds(*bind, placeholders);
                    542: 
1.99      paf       543:        const String& statement_string=r.process_to_string(statement);
1.232     moko      544:        const char* statement_cstr=statement_string.untaint_cstr(String::L_SQL, r.connection());
1.183     misha     545: 
1.240     moko      546:        String_sql_event_handlers handlers;
1.160     misha     547: 
1.240     moko      548:        r.connection()->query(statement_cstr, placeholders_count, placeholders, offset, limit, handlers, statement_string);
1.53      parser    549:        
1.141     paf       550:        if(bind)
                    551:                unmarshal_bind_updates(*bind, placeholders_count, placeholders);
                    552: 
1.65      parser    553:        if(!handlers.got_cell)
                    554:                return 0; // no lines, caller should return second param[default value]
1.62      parser    555: 
1.208     moko      556:        return handlers.result;
1.53      parser    557: }
                    558: 
1.126     paf       559: static void _sql(Request& r, MethodParams& params) {
1.53      parser    560: 
1.126     paf       561:        Value* default_code;
1.204     moko      562:        const String* string=sql_result_string(r, params, default_code);
1.62      parser    563:        if(!string) {
1.81      parser    564:                if(default_code) {
1.99      paf       565:                        string=&r.process_to_string(*default_code);
1.68      parser    566:                } else
1.238     moko      567:                        throw Exception(PARSER_RUNTIME, 0, "produced no result, but no default option specified");
1.62      parser    568:        }
1.100     paf       569: 
1.233     moko      570:        r.write(*string);
1.53      parser    571: }
                    572: 
1.126     paf       573: static void _replace(Request& r, MethodParams& params) {
                    574:        const String& src=GET_SELF(r, VString).string();
1.71      parser    575: 
1.201     misha     576:        if(params.count()==1) {
                    577:                // ^string.replace[table]
1.248     moko      578:                if(Table* table=params.as_table(0, "param")){
                    579:                        Dictionary dict(*table);
                    580:                        r.write(src.replace(dict));
                    581:                } else
                    582:                        r.write(src);
1.201     misha     583:        } else {
                    584:                // ^string.replace[from-string;to-string]
1.238     moko      585:                Dictionary dict(params.as_string(0, "from must be string"), params.as_string(1, "to must be string"));
1.233     moko      586:                r.write(src.replace(dict));
1.201     misha     587:        }
1.71      parser    588: 
                    589: }
1.79      parser    590: 
1.126     paf       591: static void _save(Request& r, MethodParams& params) {
1.189     misha     592:        bool do_append=false;
                    593:        Charset* asked_charset=0;
                    594: 
                    595:        size_t file_name_index=0;
1.214     moko      596:        if(params.count()>1) {
1.189     misha     597:                if(HashStringValue* options=params.as_no_junction(1, "second parameter should be string or hash").get_hash()){
1.205     misha     598:                        // ^file.save[filespec;$.charset[] $.append(true)]
1.190     misha     599:                        int valid_options=0;
1.189     misha     600:                        if(Value* vcharset_name=options->get(PA_CHARSET_NAME)){
1.229     moko      601:                                asked_charset=&pa_charsets.get(vcharset_name->as_string());
1.189     misha     602:                                valid_options++;
                    603:                        }
                    604:                        if(Value* vappend=options->get(MODE_APPEND)){
                    605:                                do_append=vappend->as_bool();
                    606:                                valid_options++;
                    607:                        }
                    608:                        if(valid_options != options->count())
1.194     misha     609:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.189     misha     610:                } else {
1.205     misha     611:                        // ^file.save[append;filespec]
1.189     misha     612:                        const String& mode=params.as_string(0, "mode must be string");
                    613:                        if(mode==MODE_APPEND){
                    614:                                do_append=true;
                    615:                                file_name_index++;
                    616:                        } else
                    617:                                throw Exception(PARSER_RUNTIME,
                    618:                                        &mode,
                    619:                                        "unknown mode, must be 'append'");
                    620:                }
1.214     moko      621:        }
1.79      parser    622: 
1.189     misha     623:        const String& file_name=params.as_string(file_name_index, FILE_NAME_MUST_BE_STRING);
1.126     paf       624:        const String& src=GET_SELF(r, VString).string();
1.79      parser    625: 
1.209     moko      626:        String::Body sbody=src.cstr_to_string_body_untaint(String::L_AS_IS, r.connection(false), &r.charsets);
1.87      paf       627: 
1.79      parser    628:        // write
1.246     moko      629:        file_write(r.charsets, r.full_disk_path(file_name), sbody.cstr(), sbody.length(), true, do_append, asked_charset);
1.79      parser    630: }
                    631: 
1.126     paf       632: static void _normalize(Request& r, MethodParams&) {
                    633:        const String& src=GET_SELF(r, VString).string();
                    634: 
1.233     moko      635:        r.write(src);
1.109     paf       636: }
                    637: 
1.133     paf       638: static void _trim(Request& r, MethodParams& params) {
                    639:        const String& src=GET_SELF(r, VString).string();
                    640: 
                    641:        String::Trim_kind kind=String::TRIM_BOTH;
1.176     misha     642:        size_t params_count=params.count();
1.133     paf       643:        const char* chars=0;
1.176     misha     644:        if(params_count>0) {
                    645:                const String& skind=params.as_string(0, "'where' must be string");
1.214     moko      646:                if(!skind.is_empty()) {
1.162     misha     647:                        if(skind==TRIM_BOTH_OPTION)
                    648:                                kind=String::TRIM_BOTH;
                    649:                        else if(skind==TRIM_START_OPTION || skind=="start")
1.137     paf       650:                                kind=String::TRIM_START;
1.162     misha     651:                        else if(skind==TRIM_END_OPTION || skind=="end")
1.137     paf       652:                                kind=String::TRIM_END;
1.218     moko      653:                        else if(params_count==1)
                    654:                                chars=skind.cstr();
1.137     paf       655:                        else
1.238     moko      656:                                throw Exception(PARSER_RUNTIME, &skind, "'kind' must be one of " TRIM_START_OPTION ", " TRIM_BOTH_OPTION ", " TRIM_END_OPTION);
1.214     moko      657:                }
1.133     paf       658: 
1.176     misha     659:                if(params_count>1) {
1.136     paf       660:                        const String& schars=params.as_string(1, "'chars' must be string");
1.178     misha     661:                        if(!schars.is_empty())
1.137     paf       662:                                chars=schars.cstr();
1.136     paf       663:                }
1.133     paf       664:        }
                    665: 
1.233     moko      666:        r.write(src.trim(kind, chars, &r.charsets.source()));
1.133     paf       667: }
                    668: 
1.241     moko      669: Base64Options base64_encode_options(Request& r, HashStringValue* options) {
                    670:        Base64Options result;
                    671:        if(options) {
                    672:                int valid_options=0;
                    673:                for(HashStringValue::Iterator i(*options); i; i.next()) {
                    674:                        String::Body key=i.key();
                    675:                        Value* value=i.value();
                    676:                        if(key == "pad") {
                    677:                                result.pad=r.process(*value).as_bool();
                    678:                                valid_options++;
                    679:                        } else if(key == "wrap") {
                    680:                                result.wrap=r.process(*value).as_bool();
                    681:                                valid_options++;
                    682:                        } else if(key == "url-safe") {
                    683:                                if(r.process(*value).as_bool())
                    684:                                        result.set_url_safe_abc();
                    685:                                valid_options++;
                    686:                        }
                    687:                }
                    688: 
                    689:                if(valid_options != options->count())
                    690:                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    691:        }
                    692:        return result;
                    693: }
                    694: 
                    695: Base64Options base64_decode_options(Request& r, HashStringValue* options) {
                    696:        Base64Options result;
                    697:        if(options) {
                    698:                int valid_options=0;
                    699:                for(HashStringValue::Iterator i(*options); i; i.next() ) {
                    700:                        String::Body key=i.key();
                    701:                        Value* value=i.value();
                    702:                        if(key == "pad") {
                    703:                                result.pad=r.process(*value).as_bool();
                    704:                                valid_options++;
                    705:                        } else if(key == "strict") {
                    706:                                result.strict=r.process(*value).as_bool();
                    707:                                valid_options++;
                    708:                        } else if(key == "url-safe") {
                    709:                                if(r.process(*value).as_bool())
                    710:                                        result.set_url_safe_abc();
                    711:                                valid_options++;
                    712:                        }
                    713:                }
                    714: 
                    715:                if(valid_options != options->count())
                    716:                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    717:        }
                    718:        return result;
                    719: }
                    720: 
1.146     paf       721: static void _base64(Request& r, MethodParams& params) {
1.219     moko      722:        if(&r.get_self() == string_class) {
1.241     moko      723:                // decode: ^string:base64[encoded[;options]]
1.219     moko      724:                const char* cstr=params.count() ? params.as_string(0, PARAMETER_MUST_BE_STRING).cstr() : "";
1.241     moko      725:                Base64Options options = base64_decode_options(r, params.count() > 1 ? params.as_hash(1) : NULL);
                    726: 
1.169     misha     727:                char* decoded=0;
1.243     moko      728:                size_t length=pa_base64_decode(cstr, strlen(cstr), decoded, options);
1.202     misha     729: 
1.169     misha     730:                if(decoded && length){
1.242     moko      731:                        if(memchr(decoded, 0, length))
                    732:                                throw Exception(PARSER_RUNTIME, 0, "Invalid \\x00 character found while decoding to string. Decode to file instead.");
1.169     misha     733: 
                    734:                        fix_line_breaks(decoded, length);
1.242     moko      735: 
1.179     misha     736:                        if(length)
1.233     moko      737:                                r.write(*new String(decoded, String::L_TAINTED));
1.169     misha     738:                }
1.147     paf       739:        } else {
1.241     moko      740:                // encode: ^str.base64[options]
1.148     paf       741:                VString& self=GET_SELF(r, VString);
                    742:                const char* cstr=self.string().cstr();
1.241     moko      743:                Base64Options options = base64_encode_options(r, params.count() ? params.as_hash(0) : NULL);
                    744:                const char* encoded=pa_base64_encode(cstr, strlen(cstr), options);
                    745:                r.write(*new String(encoded, String::L_TAINTED /*once ?param=base64(something) was needed*/ ));
1.146     paf       746:        }
                    747: }
                    748: 
1.215     moko      749: static void _idna(Request& r, MethodParams& params) {
1.219     moko      750:        if(&r.get_self() == string_class) {
1.215     moko      751:                // decode: ^string:idna[encoded]
1.219     moko      752:                const char* cstr=params.count() ? params.as_string(0, PARAMETER_MUST_BE_STRING).cstr() : "";
1.233     moko      753:                r.write(*new String(pa_idna_decode(cstr, r.charsets.source()), String::L_TAINTED));
1.215     moko      754:        } else {
                    755:                // encode: ^str.idna[]
                    756:                VString& self=GET_SELF(r, VString);
                    757:                const char* cstr=self.string().cstr();
1.233     moko      758:                r.write(*new String(pa_idna_encode(cstr, r.charsets.source()), String::L_TAINTED));
1.215     moko      759:        }
                    760: }
                    761: 
1.220     moko      762: static void _js_escape(Request& r, MethodParams&){
1.167     misha     763:        const String& src=GET_SELF(r, VString).string();
1.233     moko      764:        r.write(src.escape(r.charsets.source()));
1.167     misha     765: }
                    766: 
1.220     moko      767: static void _js_unescape(Request& r, MethodParams& params){
1.167     misha     768:        const String& src=params.as_string(0, PARAMETER_MUST_BE_STRING);
1.193     misha     769:        if(const char* result=unescape_chars(src.cstr(), src.length(), &r.charsets.source(), true))
1.233     moko      770:                r.write(*new String(result, String::L_TAINTED));
1.167     misha     771: }
                    772: 
1.220     moko      773: static void _unescape(Request& r, MethodParams& params){
                    774:        const String& mode=params.as_string(0, MODE_MUST_NOT_BE_CODE);
                    775:        const String& src=params.as_string(1, PARAMETER_MUST_BE_STRING);
                    776: 
                    777:        Charset* from_charset=&r.charsets.client();
                    778: 
                    779:        if(params.count() > 2)
                    780:                if(HashStringValue* options=params.as_hash(2)) {
                    781:                        int valid_options=0;
                    782:                        if(Value* vcharset_name=options->get(PA_CHARSET_NAME)){
1.229     moko      783:                                from_charset=&pa_charsets.get(vcharset_name->as_string());
1.220     moko      784:                                valid_options++;
                    785:                        }
                    786:                        if(valid_options!=options->count())
                    787:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    788:                }
                    789: 
                    790:        bool mode_js;
                    791:        if(mode==UNESCAPE_MODE_JS){
                    792:                mode_js=true;
                    793:        } else if(mode==UNESCAPE_MODE_URI){
                    794:                mode_js=false;
                    795:        } else {
1.228     moko      796:                throw Exception(PARSER_RUNTIME, &mode, "is invalid mode, must be either '" UNESCAPE_MODE_JS "' or '" UNESCAPE_MODE_URI "'");
1.220     moko      797:        }
                    798: 
                    799:        const char* unescaped=unescape_chars(src.cstr(), src.length(), from_charset, mode_js);
                    800:        if(*unescaped){
1.221     moko      801:                const String* result=new String(Charset::transcode(unescaped, *from_charset, r.charsets.source()), String::L_TAINTED);
1.233     moko      802:                r.write(*result);
1.220     moko      803:        }
                    804: }
                    805: 
1.225     moko      806: static void _contains(Request& r, MethodParams& params) {
                    807:        // empty or whitespace string is hash compatible
                    808:        GET_SELF(r, VString).get_element(params.as_string(0, "key must be string"));
                    809:        // ignoring result as it allways null
1.233     moko      810:        r.write(VBool::get(false));
1.225     moko      811: }
                    812: 
1.41      paf       813: // constructor
                    814: 
1.126     paf       815: MString::MString(): Methoded("string") {
1.1       paf       816:        // ^string.length[]
1.41      paf       817:        add_native_method("length", Method::CT_DYNAMIC, _length, 0, 0);
1.6       paf       818:        
1.1       paf       819:        // ^string.int[]
1.72      parser    820:        // ^string.int(default)
                    821:        add_native_method("int", Method::CT_DYNAMIC, _int, 0, 1);
1.1       paf       822:        // ^string.double[]
1.72      parser    823:        // ^string.double(default)
                    824:        add_native_method("double", Method::CT_DYNAMIC, _double, 0, 1);
1.151     misha     825:        // ^void.bool[]
                    826:        // ^void.bool(default)
                    827:        add_native_method("bool", Method::CT_DYNAMIC, _bool, 0, 1);
1.9       paf       828: 
1.165     misha     829:        // ^string.format[format]
1.41      paf       830:        add_native_method("format", Method::CT_DYNAMIC, _string_format, 1, 1);
1.14      paf       831: 
1.15      paf       832:        // ^string.left(n)
1.41      paf       833:        add_native_method("left", Method::CT_DYNAMIC, _left, 1, 1);
1.15      paf       834:        // ^string.right(n)
1.41      paf       835:        add_native_method("right", Method::CT_DYNAMIC, _right, 1, 1);
1.165     misha     836:        // ^string.mid(p)
1.15      paf       837:        // ^string.mid(p;n)
1.82      parser    838:        add_native_method("mid", Method::CT_DYNAMIC, _mid, 1, 2);
1.16      paf       839: 
                    840:        // ^string.pos[substr]
1.165     misha     841:        // ^string.pos[substr](n)
                    842:        add_native_method("pos", Method::CT_DYNAMIC, _pos, 1, 2);
1.17      paf       843: 
1.118     paf       844:        // ^string.split[delim]
                    845:        // ^string.split[delim][options]
1.156     misha     846:        // ^string.split[delim][options][column name]
                    847:        add_native_method("split", Method::CT_DYNAMIC, _split, 1, 3);
1.236     moko      848:        // old names for backward compatibility
                    849:        // ^string.lsplit[delim]
                    850:        add_native_method("lsplit", Method::CT_DYNAMIC, _lsplit, 1, 1);
                    851:        // ^string.rsplit[delim]
                    852:        add_native_method("rsplit", Method::CT_DYNAMIC, _rsplit, 1, 1);
                    853: 
1.32      paf       854:        // ^string.match[regexp][options]
                    855:        // ^string.match[regexp][options]{replacement-code}
1.192     misha     856:        // ^string.match[regexp][options]{replacement-code}{code-if-nothing-is-found}
                    857:        add_native_method("match", Method::CT_DYNAMIC, _match, 1, 4);
1.49      parser    858: 
1.165     misha     859:        // ^string.upper[]
1.49      parser    860:        add_native_method("upper", Method::CT_DYNAMIC, _upper, 0, 0);
1.165     misha     861:        // ^string.lower[]
1.49      parser    862:        add_native_method("lower", Method::CT_DYNAMIC, _lower, 0, 0);
1.53      parser    863: 
1.189     misha     864:        // ^string:sql{query}
                    865:        // ^string:sql{query}[options hash]
1.67      parser    866:        add_native_method("sql", Method::CT_STATIC, _sql, 1, 2);
1.71      parser    867: 
                    868:        // ^string.replace[table]
1.201     misha     869:        add_native_method("replace", Method::CT_DYNAMIC, _replace, 1, 2);
1.79      parser    870: 
1.189     misha     871:        // ^string.save[append][file]
                    872:        // ^string.save[file]
                    873:        // ^string.save[file][$.append(true) $.charset[...]]
1.87      paf       874:        add_native_method("save", Method::CT_DYNAMIC, _save, 1, 2);
1.109     paf       875: 
1.112     paf       876:        // ^string.normalize[]  
                    877:        add_native_method("normalize", Method::CT_DYNAMIC, _normalize, 0, 0);
1.133     paf       878: 
                    879:        // ^string.trim[[start|both|end][;chars]]
                    880:        add_native_method("trim", Method::CT_DYNAMIC, _trim, 0, 2);
1.139     paf       881: 
1.146     paf       882:        // ^string.base64[] << encode
1.215     moko      883:        // ^string:base64[encoded string] << decode
1.202     misha     884:        add_native_method("base64", Method::CT_ANY, _base64, 0, 2);
1.167     misha     885: 
1.215     moko      886:        // ^string.idna[] << encode
                    887:        // ^string:idna[encoded string] << decode
                    888:        add_native_method("idna", Method::CT_ANY, _idna, 0, 1);
                    889: 
1.168     misha     890:        // ^string.js-escape[]
1.220     moko      891:        add_native_method("js-escape", Method::CT_DYNAMIC, _js_escape, 0, 0);
1.189     misha     892: 
1.168     misha     893:        // ^string:js-unescape[escaped%uXXXXstring]
1.220     moko      894:        add_native_method("js-unescape", Method::CT_STATIC, _js_unescape, 1, 1);
                    895: 
                    896:        // ^string:unescape[js|uri;escaped;$.charset[...]]
                    897:        add_native_method("unescape", Method::CT_STATIC, _unescape, 2, 3);
1.225     moko      898: 
                    899:        // ^string.contains[key] for hash compatibility
                    900:        add_native_method("contains", Method::CT_DYNAMIC, _contains, 1, 1);
1.220     moko      901: }

E-mail: