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

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

E-mail: