Annotation of parser3/src/classes/date.C, revision 1.46

1.1       parser      1: /** @file
                      2:        Parser: @b date parser class.
                      3: 
1.46    ! paf         4:        Copyright (c) 2001-2003 ArtLebedev Group (http://www.artlebedev.com)
1.16      paf         5:        Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.32      paf         6: */
1.1       parser      7: 
1.46    ! paf         8: static const char* IDENT_DATE_C="$Date: 2003/04/11 16:05:43 $";
1.1       parser      9: 
                     10: #include "classes.h"
1.46    ! paf        11: #include "pa_vmethod_frame.h"
        !            12: 
1.1       parser     13: #include "pa_request.h"
                     14: #include "pa_vdouble.h"
                     15: #include "pa_vdate.h"
1.10      parser     16: #include "pa_vtable.h"
1.1       parser     17: 
                     18: // class
                     19: 
1.46    ! paf        20: class MDate: public Methoded {
1.1       parser     21: public: // VStateless_class
1.46    ! paf        22:        Value* create_new_value() { return new VDate(0); }
1.1       parser     23: 
                     24: public:
1.46    ! paf        25:        MDate();
1.1       parser     26: public: // Methoded
                     27:        bool used_directly() { return true; }
                     28: };
                     29: 
1.46    ! paf        30: // global variable
        !            31: 
        !            32: DECLARE_CLASS_VAR(date, new MDate, 0);
        !            33: 
        !            34: // helpers
        !            35: 
        !            36: class Date_calendar_table_template_columns: public ArrayString {
        !            37: public:
        !            38:        Date_calendar_table_template_columns(): ArrayString(6+2) {
        !            39:                for(int i=0; i<=6; i++) {
        !            40:                        char *cname=new(PointerFreeGC) char[1/*strlen("6")*/+1/*terminating 0*/];
        !            41:                        *this+=new String(cname, sprintf(cname, "%d", i)); // .i column name
        !            42:                }
        !            43:                *this+=new String("week");
        !            44:                *this+=new String("year");
        !            45:        }
        !            46: };
        !            47: 
        !            48: 
        !            49: Table date_calendar_table_template(new Date_calendar_table_template_columns);
        !            50: 
1.1       parser     51: // methods
                     52: 
1.46    ! paf        53: static void _now(Request& r, MethodParams& params) {
        !            54:        VDate& vdate=GET_SELF(r, VDate);
1.23      paf        55: 
                     56:        time_t t=time(0);
1.46    ! paf        57:        if(params.count()==1) // ^now(offset)
        !            58:                t+=(time_t)round(params.as_double(0, "offset must be double", r)*SECS_PER_DAY);
1.23      paf        59:        
1.46    ! paf        60:        vdate.set_time(t);
1.1       parser     61: }
                     62: 
1.28      paf        63: static int NN_year_to_NNNN(int year) {
                     64:        if(year<70) // 0..69 -> 100..169 [2000..2069]
                     65:                year+=100;
                     66:        if(year>=1900)
                     67:                year-=1900;
                     68:        return year;
                     69: }
                     70: 
1.41      paf        71: // 2002-04-25 18:14:00
                     72: // 18:14:00
                     73: // 2002:04:25 [+maybe time]
1.46    ! paf        74: time_t cstr_to_time_t(char *cstr, bool fail_on_error) { // used in image.C
1.41      paf        75:        char *cur=cstr;
                     76:        int date_delim=isdigit(cur[0])&&isdigit(cur[1])&&isdigit(cur[2])&&isdigit(cur[3])&&cur[4]==':'?':'
                     77:                :'-';
1.46    ! paf        78:        const char* year=lsplit(&cur, date_delim);
        !            79:        const char* month=lsplit(&cur, date_delim);
        !            80:        const char* mday=lsplit(&cur, ' ');
1.41      paf        81:        if(!month)
                     82:                cur=cstr;
1.46    ! paf        83:        const char* hour=lsplit(&cur, ':');
        !            84:        const char* min=lsplit(&cur, ':');
        !            85:        const char* sec=cur;
1.41      paf        86: 
                     87:        tm tmIn={0};
                     88:        tmIn.tm_isdst=-1;
                     89:        if(!month)
                     90:                if(min) {
                     91:                        year=mday=0; // HH:MM
                     92:                        time_t t=time(0);
                     93:                        tm *tmNow=localtime(&t);
                     94:                        tmIn.tm_year=tmNow->tm_year;
                     95:                        tmIn.tm_mon=tmNow->tm_mon;
                     96:                        tmIn.tm_mday=tmNow->tm_mday;
                     97:                        goto date_part_set;
                     98:                } else
                     99:                        hour=min=sec=0; // not YYYY- & not HH: = just YYYY                                      
                    100:        tmIn.tm_year=NN_year_to_NNNN(atoi(year));
                    101:        tmIn.tm_mon=month?atoi(month)-1:0;
                    102:        tmIn.tm_mday=mday?atoi(mday):1;
                    103: date_part_set:
                    104:        tmIn.tm_hour=hour?atoi(hour):0;
                    105:        tmIn.tm_min=min?atoi(min):0;
                    106:        tmIn.tm_sec=sec?atoi(sec):0;
                    107:        time_t result=mktime(&tmIn);
                    108:        if(result<0)
1.46    ! paf       109:                if(fail_on_error)
1.41      paf       110:                        throw Exception(0,
1.46    ! paf       111:                                0, //report_error_origin,
1.41      paf       112:                                "invalid datetime");
                    113: 
                    114:        return result;
                    115: }
                    116: 
1.46    ! paf       117: static void _create(Request& r, MethodParams& params) {
        !           118:        VDate& vdate=GET_SELF(r, VDate);
1.1       parser    119: 
1.23      paf       120:        time_t t;
1.46    ! paf       121:        if(params.count()==1) { 
1.31      paf       122:                // ^create[2002-04-25 18:14:00]
                    123:                // ^create[18:14:00]
1.46    ! paf       124:                if(const String* sdate=params[0].get_string())
        !           125:                        t=cstr_to_time_t(sdate->cstrm(), true);
1.41      paf       126:                else { // ^create(float days)
1.46    ! paf       127:                        t=(time_t)round(params.as_double(0, "float days must be double", r)*SECS_PER_DAY);
1.28      paf       128:                        if(t<0 || !localtime(&t))
                    129:                                throw Exception(0,
1.46    ! paf       130:                                        0,
1.28      paf       131:                                        "invalid datetime");
                    132:                }
1.46    ! paf       133:        } else if(params.count()>=2) { // ^create(y;m;d[;h[;m[;s]]])
1.1       parser    134:                tm tmIn={0};
                    135:                tmIn.tm_isdst=-1;
1.46    ! paf       136:                tmIn.tm_year=NN_year_to_NNNN(params.as_int(0, "year must be int", r));
        !           137:                tmIn.tm_mon=params.as_int(1, "month must be int", r)-1;
        !           138:                tmIn.tm_mday=params.count()>2?params.as_int(2, "mday must be int", r):1;
        !           139:                if(params.count()>3) tmIn.tm_hour=params.as_int(3, "hour must be int", r);
        !           140:                if(params.count()>4) tmIn.tm_min=params.as_int(4, "minutes must be int", r);
        !           141:                if(params.count()>5) tmIn.tm_sec=params.as_int(5, "seconds must be int", r);
1.23      paf       142:                t=mktime(&tmIn);
                    143:                if(t<0)
1.22      paf       144:                        throw Exception(0,
1.46    ! paf       145:                                0,
1.1       parser    146:                                "invalid datetime");
                    147:        } else
1.22      paf       148:                throw Exception("parser.runtime",
1.46    ! paf       149:                        0,
1.24      paf       150:                        "invalid params count, must be 1 or >=2");
1.46    ! paf       151:        vdate.set_time(t);
1.1       parser    152: }
                    153: 
1.46    ! paf       154: static void _sql_string(Request& r, MethodParams&) {
        !           155:        VDate& vdate=GET_SELF(r, VDate);
1.2       parser    156:        int size=1+ 4+1+2+1+2 +1+ 2+1+2+1+2 +1 +1;
1.46    ! paf       157:        char *buf=new(PointerFreeGC) char[size];
        !           158:        time_t time=vdate.get_time();
1.14      paf       159:        size=strftime(buf, size, "%Y-%m-%d %H:%M:%S", localtime(&time));
1.1       parser    160:        
1.46    ! paf       161:        r.write_assign_lang(String(buf, size));
1.1       parser    162: }
                    163: 
                    164: 
1.46    ! paf       165: static void _roll(Request& r, MethodParams& params) {
        !           166:        VDate& vdate=GET_SELF(r, VDate);
1.1       parser    167: 
1.46    ! paf       168:        const String& what=params.as_string(0, "'what' must be string");
1.43      paf       169:        int oyear=0;
                    170:        int omonth=0;
                    171:        int oday=0;
1.1       parser    172:        int *offset;
                    173:        if(what=="year") offset=&oyear;
                    174:        else if(what=="month") offset=&omonth;
                    175:        else if(what=="day") offset=&oday;
                    176:        else
1.22      paf       177:                throw Exception("parser.runtime",
1.1       parser    178:                        &what,
                    179:                        "must be year|month|day");
                    180:        
1.46    ! paf       181:        *offset=params.as_int(1, "offset must be int", r);
1.1       parser    182: 
1.46    ! paf       183:        time_t self_time=vdate.get_time();
1.13      paf       184:        tm tmIn=*localtime(&self_time);
                    185:        tm tmSaved=tmIn;
1.43      paf       186:        int adjust_day=0;
                    187:        time_t t_changed_date;
                    188:        while(true) {
                    189:                tmIn.tm_year+=oyear;
                    190:                tmIn.tm_mon+=omonth;
                    191:                tmIn.tm_mday+=oday+adjust_day;
                    192:                tmIn.tm_hour=24/2; 
                    193:                tmIn.tm_min=0;
                    194:                tmIn.tm_sec=0;
1.44      paf       195:                int saved_mon=(tmIn.tm_mon+12*100)%12; // crossing year boundary backwards
1.43      paf       196:                t_changed_date=mktime/*normalizetime*/(&tmIn);
                    197:                if(t_changed_date<0)
                    198:                        throw Exception(0,
1.46    ! paf       199:                                0,
1.43      paf       200:                                "bad resulting time (rolled out of valid date range)");
1.46    ! paf       201:                if(oday==0 && tmIn.tm_mon!=saved_mon/*but it changed*/) {
1.43      paf       202:                        if(adjust_day <= -3/*31->28 max, so never, but...*/)
                    203:                                throw Exception(0,
1.46    ! paf       204:                                        0,
1.43      paf       205:                                        "bad resulting time (day hole still with %d day adjustment)", adjust_day );
                    206:                        
                    207:                        tmIn=tmSaved; // restoring
                    208:                        --adjust_day; //retrying with prev day
                    209:                } else
                    210:                        break;                  
                    211:        }
1.13      paf       212: 
1.43      paf       213:        tm *tmOut=localtime(&t_changed_date);
1.13      paf       214:        if(!tmOut)
1.22      paf       215:                throw Exception(0,
1.46    ! paf       216:                        0,
1.43      paf       217:                        "bad resulting time (seconds from epoch=%d)", t_changed_date);
1.13      paf       218:     
1.43      paf       219:        tmOut->tm_hour=tmSaved.tm_hour;
                    220:        tmOut->tm_min=tmSaved.tm_min;
                    221:        tmOut->tm_sec=tmSaved.tm_sec;
1.20      paf       222:        tmOut->tm_isdst=-1; 
1.13      paf       223:        {
1.43      paf       224:                time_t t_changed_time=mktime/*normalizetime*/(tmOut);
                    225:                /*autofix: in msk timezone last sunday of april hour hole: [2am->3am)
1.21      paf       226:                if(
                    227:                        tmOut->tm_hour!=tmSaved.tm_hour
                    228:                        ||tmOut->tm_min!=tmSaved.tm_min)
1.22      paf       229:                        throw Exception(0,
1.46    ! paf       230:                                0,
1.24      paf       231:                                "bad resulting time (hour hole)");
1.43      paf       232:                */
1.21      paf       233: 
1.43      paf       234:                if(t_changed_time<0)
1.22      paf       235:                        throw Exception(0,
1.46    ! paf       236:                                0,
1.21      paf       237:                                "bad resulting time (after reconstruction)");
1.13      paf       238:                
1.46    ! paf       239:                vdate.set_time(t_changed_time);
1.13      paf       240:        }
1.1       parser    241: }
                    242: 
1.46    ! paf       243: static Table& fill_month_days(Request& r, MethodParams& params, bool rus){
1.45      paf       244:        Table::Action_options table_options;
1.46    ! paf       245:        Table& result=*new Table(date_calendar_table_template, table_options);
        !           246:        
        !           247:        int year=params.as_int(1, "year must be int", r);
        !           248:        int month=max(1, min(params.as_int(2, "month must be int", r), 12)) -1;
1.43      paf       249:        
                    250:        tm tmIn={0, 0, 0, 1, month, year-1900};
                    251:        time_t t=mktime(&tmIn);
1.10      parser    252:        if(t<0)
1.22      paf       253:                throw Exception(0, 
1.46    ! paf       254:                        0, 
1.10      parser    255:                        "invalid date");
1.43      paf       256:        tm *tmOut=localtime(&t);
                    257:        
                    258:        int weekDay1=tmOut->tm_wday;
1.10      parser    259:        if(rus) 
                    260:                weekDay1=weekDay1?weekDay1-1:6; //sunday last
1.43      paf       261:        int monthDays=getMonthDays(year, month);
                    262:        
                    263:        for(int _day=1-weekDay1; _day<=monthDays;) {
1.46    ! paf       264:                Table::element_type row(new ArrayString(7));
1.34      paf       265:                // calculating year week no [1..54]
                    266:                char *weekno_buf;
                    267:                size_t weekno_size;
1.36      paf       268:                int weekyear;
1.34      paf       269:                // 0..6 week days-cells fill with month days
1.43      paf       270:                for(int wday=0; wday<7; wday++, _day++) {
1.46    ! paf       271:                        String* cell=new String;
1.10      parser    272:                        if(_day>=1 && _day<=monthDays) {
1.46    ! paf       273:                                char *buf=new(PointerFreeGC) char[2+1]; 
        !           274:                                cell->append_know_length(buf, sprintf(buf, "%02d", _day), String::L_CLEAN);
        !           275:                        }
        !           276:                        *row+=cell;            
1.34      paf       277: 
                    278:                        if(wday==(rus?3:4)/*thursday*/) {
                    279:                                tm tms={0,0,0,  _day, month, year-1900};
                    280:                                /*normalize*/mktime(&tms);
                    281: 
1.36      paf       282:                                weekyear=tms.tm_year+1900;
                    283: 
1.35      paf       284:                                const int weekno_buf_size=2+1/*for stupid snprintfs*/ +1;
1.34      paf       285: 
                    286:                                // http://www.merlyn.demon.co.uk/weekinfo.htm
                    287:                                const int FirstThurs[] = {7,5,4,3,2,7,6,5,4,2,1,7,6,4,3,2,1,6,5,4,3,1,7,6,5,3,2,1};
1.36      paf       288:                                int n=1 + (tms.tm_yday-(FirstThurs[weekyear % 28]-3))/7;
1.46    ! paf       289:                                weekno_buf=new(PointerFreeGC) char[weekno_buf_size];
1.34      paf       290:                                weekno_size=snprintf(weekno_buf, weekno_buf_size, "%02d", n);
                    291:                        }
                    292:                
1.10      parser    293:         }
1.34      paf       294:                // appending year week no
1.46    ! paf       295:                *row+=new String(weekno_buf, weekno_size);
1.36      paf       296:                // appending year week year
                    297:                {
1.46    ! paf       298:                        char* buf=new(PointerFreeGC) char[4+1]; 
        !           299:                        *row+=new String(buf, sprintf(buf, "%02d", weekyear));
1.34      paf       300:                }
1.46    ! paf       301:                result+=row;
        !           302:        }
        !           303:        
        !           304:        return result;
1.10      parser    305: }
                    306: 
1.46    ! paf       307: static Table& fill_week_days(Request& r, MethodParams& params, bool rus){
        !           308:        Table::columns_type columns(new ArrayString(4));
        !           309:        *columns+=new String("year");
        !           310:        *columns+=new String("month");
        !           311:        *columns+=new String("day");
        !           312:        *columns+=new String("weekday");
        !           313:        Table& result=*new Table(columns);
        !           314: 
        !           315:        int year=params.as_int(1, "year must be int", r);
        !           316:        int month=max(1, min(params.as_int(2, "month must be int", r), 12)) -1;
        !           317:        int day=params.as_int(3, "day must be int", r);
        !           318:        
        !           319:        tm tmIn={0, 0, 18, day, month, year-1900};
        !           320:        time_t t=mktime(&tmIn);
1.10      parser    321:        if(t<0)
1.22      paf       322:                throw Exception(0, 
1.46    ! paf       323:                        0, 
1.10      parser    324:                        "invalid date");
1.46    ! paf       325:        tm *tmOut=localtime(&t);
1.10      parser    326:     
1.46    ! paf       327:        int baseWeekDay=tmOut->tm_wday;
1.10      parser    328:        if(rus) 
                    329:                baseWeekDay=baseWeekDay?baseWeekDay-1:6; //sunday last
1.46    ! paf       330:        
        !           331:        t-=baseWeekDay*SECS_PER_DAY;
        !           332:                
        !           333:        for(int curWeekDay=0; curWeekDay<7; curWeekDay++, t+=SECS_PER_DAY) {
        !           334:                tm *tmOut=localtime(&t);
        !           335:                Table::element_type row(new ArrayString(4));
1.10      parser    336: #define WDFILL(size, value) { \
1.46    ! paf       337:                        char *buf=new(PointerFreeGC) char[size+1]; \
        !           338:                        *row+=new String(buf, sprintf(buf, "%0"#size"d", value)); \
1.10      parser    339:                }
                    340:                WDFILL(4, 1900+tmOut->tm_year);
                    341:                WDFILL(2, 1+tmOut->tm_mon);
                    342:                WDFILL(2, tmOut->tm_mday);
                    343:                WDFILL(2, tmOut->tm_wday);
1.46    ! paf       344:                result+=row;
        !           345:        }
        !           346:        
        !           347:        return result;
1.10      parser    348: }
                    349: 
1.46    ! paf       350: static void _calendar(Request& r, MethodParams& params) {
        !           351:        const String& what=params.as_string(0, "format must be strig");
1.10      parser    352:        bool rus=false;
                    353:        if(what=="rus")
                    354:                rus=true;
                    355:        else if(what=="eng")
                    356:                rus=false;
                    357:        else
1.22      paf       358:                throw Exception("parser.runtime", 
1.10      parser    359:                        &what, 
                    360:                        "must be rus|eng");
                    361: 
1.46    ! paf       362:        Table* table;
        !           363:        if(params.count()==1+2) 
        !           364:                table=&fill_month_days(r, params, rus);
1.10      parser    365:        else // 1+3
1.46    ! paf       366:                table=&fill_week_days(r, params, rus);
1.10      parser    367: 
1.46    ! paf       368:        r.write_no_lang(*new VTable(table));
1.10      parser    369: }
                    370: 
1.1       parser    371: // constructor
                    372: 
1.46    ! paf       373: MDate::MDate(): Methoded("date") {
1.1       parser    374:        // ^now[]
1.23      paf       375:        add_native_method("now", Method::CT_DYNAMIC, _now, 0, 1);
1.1       parser    376: 
1.30      paf       377:        // ^create(float days)
1.17      paf       378:        add_native_method("create", Method::CT_DYNAMIC, _create, 1, 6);
1.28      paf       379:        // old name for compatibility with <= v1.17 2002/2/18 12:13:42 paf
1.17      paf       380:        add_native_method("set", Method::CT_DYNAMIC, _create, 1, 6);
1.1       parser    381: 
1.6       parser    382:        // ^sql-string[]
1.5       parser    383:        add_native_method("sql-string", Method::CT_DYNAMIC, _sql_string, 0, 0);
1.1       parser    384: 
                    385:        // ^roll(year|month|day;+/- 1)
                    386:        add_native_method("roll", Method::CT_DYNAMIC, _roll, 2, 2);
1.10      parser    387: 
                    388:        // ^date:calendar[month|montheng;year;month]  = table
                    389:        // ^date:calendar[week|weekeng;year;month;day] = table
                    390:        add_native_method("calendar", Method::CT_STATIC, _calendar, 3, 4);
1.1       parser    391: 
                    392: }

E-mail: