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

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

E-mail: