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

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

E-mail: