<?php
    function number_correct($phone)
    {
        //get first characters
        $char_1=substr($phone,0,1); // get 1 char
        $char_2=substr($phone,1,1); // get 2 char
        $char_3=substr($phone,2,1);
        // correct number phone
        if($char_1=='+' && $char_2=='7')
        {
            $phone="7".substr($phone,2);
        }
        elseif($char_1==' ' && $char_2=='+' && $char_3=='7')
        {
            $phone="7".substr($phone,3);
        }
        elseif($char_1=='8')
        {
            $phone="7".substr($phone,1);
        }
        return $phone;
    }
    // Create masssiv userid, example user_id=>phone
    function create_masssiv_for_sendsms($users,$profile)
    {
        if(empty($users))
            return false;
        foreach($users as $id=>$val)
        {
            if($profile=='user' || $profile=='student')
            {
            $sql_get_phone="SELECT * FROM ".$profile."s WHERE ".$profile."_id='$id'";
            $row=db_request(db_execute($sql_get_phone,array(),array()));
            if($profile=='user')
                $cfield='CFIELD_'.Preferences('CURENT_USER_SMS_FIELD');
            elseif($profile=='student')
                $cfield='CFIELD_'.Preferences('CURENT_STUDENT_SMS_FIELD');
            if(empty($row[1][$cfield]))
                $empty=true;
            elseif(!empty($row[1][$cfield]))
                $empty=false;
            }
            elseif($profile=='parent')
            {
               $sql_get_phone="SELECT s.* FROM students as s,students_in_sr as sis WHERE sis.address_id='$id' and sis.student_id=s.student_id";
               $row=db_request(db_execute(db_limit($sql_get_phone,1)));
               $cfield='CFIELD_'.Preferences('CURENT_PARENT_SMS_FIELD');
               if(empty($row[1][$cfield]))
                $empty=true;
               elseif(!empty($row[1][$cfield]))
                $empty=false;
            }
            $phone=$row[1][$cfield];
            $phone=number_correct($phone);
            if($empty==false)
                $mas[$id]=$phone;
        }
        return $mas; 
    }
    // Create massiv delivering groups
    function create_massiv_groups($groups)
    {
        $people_id=array();
        $mas=array();
        if(empty($groups))
            return false;
        // id= group id, val - value checkbox (on)
        foreach($groups as $id=>$val)
        {
            $sql="SELECT * FROM personal_in_mailgroup WHERE group_id='$id'";
            $row_get_users=db_request(db_execute($sql));
            foreach($row_get_users as $num=>$zv)
            {
                $people_id+=array($row_get_users[$num]['PERSON_ID']=>$row_get_users[$num]['PROFILE2']);
            }
        }
        foreach($people_id as $id=>$profile)
        {
            $phone='';
            if($profile=='user')
            {
                $cfield="CFIELD_".Preferences('CURENT_USER_SMS_FIELD');
                $sql="SELECT * FROM users WHERE user_id='$id'";
                $row=db_request(db_execute($sql));
                if(!empty($row[1][$cfield]))
                    $phone=$row[1][$cfield];
            }
            elseif($profile=='student')
            {
                $cfield="CFIELD_".Preferences('CURENT_STUDENT_SMS_FIELD');
                $sql="SELECT * FROM students WHERE student_id='$id'";
                $row=db_request(db_execute($sql));
                if(!empty($row[1][$cfield]))
                    $phone=$row[1][$cfield];
            }
            elseif($profile=='parent')
            {
                $cfield="CFIELD_".Preferences('CURENT_PARENT_SMS_FIELD');
                $sql="SELECT s.* FROM students as s,students_in_sr as sis WHERE sis.address_id='$id' and sis.student_id=s.student_id";
                $row=db_request(db_execute(db_limit($sql,1)));
                if(!empty($row[1][$cfield]))
                    $phone=$row[1][$cfield];
            }
            if(!empty($phone))
            {
                $phone=number_correct($phone);
                $mas[$id]=$phone."/".$profile;
            }
        }
        return $mas;
    }
    // sms service SMS48
    // method- groups or users/students, value= group or student/user
    function send_sms($mas_users,$sms,$method)
    {
        $sms_profile_id=Preferences('CURRENT_SMS_PROFILE');
        //echo $sms_profile_id;
        $sql_get_sms_profile="SELECT * FROM sms_profiles WHERE ID='$sms_profile_id'";
        $row_sms_profile=db_request(db_execute($sql_get_sms_profile),array(),array());
        //$mas_users=create_masssiv($users);
        $send_status=array();
        //var_dump($mas_users);
        if ($mac_users) {
            foreach($mas_users as $id=>$number)
            {
                    if($method=='group')
                    {
                        $find='/';
                        $pos=strpos($number,$find);
                        $phone=substr($number,0,$pos);
                        //echo $phon."<br/>";
                        $profile=substr($number,$pos+1);
                        if($profile=='user' || $profile=='student')
                        {
                            $method_func='user';
                            $table=$profile."s";
                        }
                        elseif($profile=='parent')
                        {
                            $method_func='parent';
                        }
                    }
                    elseif($method=='user')
                    {
                        $table='users';
                        $profile=$method;
                        $phone=$number;
                        $method_func='user';
                    }
                    elseif($method=='student')
                    {
                        $table='students';
                        $profile=$method;
                        $phone=$number;
                        $method_func='student';
                    }
                    elseif($method=='parent')
                    {
                        $method_func='parent';
                        $phone=$number;
                    }
                    if($method_func=='parent')
                    {
                        $sql_get_fio="SELECT sr.first_name".CCAT."' '".CCAT."sr.middle_name".CCAT."' '".CCAT."sr.last_name as fullname FROM students_in_sr as sis, student_relations as sr WHERE sis.address_id='$id' and sis.person_id=sr.person_id";
                        $row_fio=db_request(db_execute($sql_get_fio));
                        //$phone=$number;
                        foreach($row_fio as $num=>$tit)
                        {
                            $fio=$row_fio[$num]['FULLNAME'].",";
                        }
                        $fio=substr($fio,0,-1);
                    }
                    if($method_func!='parent')
                    {
                        $sql_get_fio="SELECT *
                                  FROM ".$table."
                                  WHERE ".$profile."_id='$id'";
                    $row_fio=db_request(db_execute($sql_get_fio),array(),array());
                    $fio=$row_fio[1]['LAST_NAME']." ".$row_fio[1]['FIRST_NAME']." ".$row_fio[1]['MIDDLE_NAME'];
                    }
                    switch($row_sms_profile[1]['SYSTEM_NAME'])
                    {
                        case 'sms48':
                           $res=send_sms48($row_sms_profile[1]['LOGIN'],$row_sms_profile[1]['PASS'],$row_sms_profile[1]['MSG_SUBJECT'],$sms,$phone);
                           break;
                        case 'sms16':
                            $res=send_sms16($phone,$sms,$row_sms_profile[1]['LOGIN'],$row_sms_profile[1]['PASS'],$row_sms_profile[1]['MSG_SUBJECT']);
                            break;
                    }
                    if($res==1)
                    {
                        $send_status[$id]=array($fio=>'Send');
                    }
                    else
                    {
                        $send_status[$id]=array($fio=>'Error');
                    }
                    return $send_status;
            }
        }
        return $send_status;
    }
    function send_sms48($login,$pass,$subject,$sms,$phone)
    {
            $also_convert = mb_convert_encoding($sms, 'WINDOWS-1251', 'UTF-8');
            $login = $login;
            $password = $pass;
            $phone = $phone;
            //echo $phone;
            $from = $subject;
            $msg = urlencode($also_convert);
            $checksumm = md5($login.md5($password).$phone);
            $res = @file_get_contents("http://sms48.ru/send_sms.php?login=$login&to=$phone&msg=$msg&from=$from&check2=$checksumm");
            return $res;
    }
    function balance_sms16($login,$password)
    {
    $src = '<?xml version="1.0" encoding="utf-8" ?>
    <request>
       <security>
         <login value="'.$login.'" />
         <password value="'.$password.'" />
       </security>
    </request>';
         $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: text/xml; charset=utf-8'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CRLF, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSLVERSION,3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $src);
        curl_setopt($ch, CURLOPT_URL, 'https://my.sms16.ru/xml/balance.php');
        $result = curl_exec($ch);
        $res = $result;
        curl_close($ch);
        return $res;
    }
    function send_sms16($number,$text,$login,$pass,$subject)
    {
        $number=number_correct($number);
        $src = '<?xml version="1.0" encoding="utf-8"  ?>
        <request>
       <message>
         <sender>'.$subject.'</sender>
         <text>'.$text.'</text>
         <abonent phone="'.$number.'" number_sms="1"/>
       </message>
       <security>
         <login value="'.$login.'" />
         <password value="'.$pass.'" />
       </security>
    </request> ';
        $res = '';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: text/xml;
    charset=utf-8'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CRLF, true);
        curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_SSLVERSION,3);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $src);
        curl_setopt($ch, CURLOPT_URL, 'https://my.sms16.ru/xml/');
        $result = curl_exec($ch);
        $res = $result;
        curl_close($ch);
        if($res=="send")
            $res=1;
        else
            $res="error";
        return $res;
    }
    function send_free($phone,$email,$sms,$operator)
    {
        $phone=number_correct($phone);
        $mail_addr = $phone; 
        $text = $sms; 
        $from_address=$email;
        $subject=_('Grade');
        //$from_name="integral";
        //$to_name="integral";
        //$options="cc";
        switch ($operator) 
        { 
        case "megafon":
        $mail_addr .= "@megafon.ru"; 
        break; 
        case "beeline":
        $mail_addr .= "@sms.beemail.ru"; 
        break; 
        case "mts":
        $mail_addr .= "@sms.mtslife.ru"; 
        break;  
        case "tele":
        $mail_addr .= "@omsk.tele2.ru "; 
        break; 
        }
        echo $mail_addr; 
        //$mail_addr = "andy_1792@mail.ru";
        $res=SendEmail($mail_addr, $to_name, $from_address, $from_name, $subject, $sms, $options);
        /*{
            $res=1;
        }
        else
            $res="error";*/
        //echo $res;
        return $res;        
    }
    function balance_sms48($login,$password)
    {
        $check = md5($login.md5($password));
        $balance = file_get_contents("http://sms48.ru/get_balance?login=$login&check=$check");
        return $balance;
    }
    function get_balance($id)
    {
        $sql_get_profile="SELECT * FROM sms_profiles WHERE ID='$id'";
        $row_profile=db_request(db_execute($sql_get_profile));
        switch($row_profile[1]['SYSTEM_NAME'])
        {
            case 'sms48':
                $balance=balance_sms48($row_profile[1]['LOGIN'],$row_profile[1]['PASS']);
                $balance.=" смс";
                break;
            case 'sms16':
                $balance=balance_sms16($row_profile[1]['LOGIN'],$row_profile[1]['PASS']);
                $balance.=" руб.";
                break;
        }
        return $balance;
    }
    function get_provider($phone)
    {
        $phone=number_correct($phone);
        $chars=substr($phone,1,3);
        $beeline=array('902','903','904','905','906','907','908','909','961','963','964','965','962');
        $mts=array('910','911','912','913','914','915','916','917','918','919','980','981','982','983','984','985','987','988','989');
        $megafon=array();
        $tele=array();
        if(array_search($chars, $beeline)!=false)
          return 'beeline';
        elseif(array_search($chars, $mts)!=false)
          return 'mts';
        elseif(array_search($chars, $megafon)!=false)
          return 'megafon';
        elseif(array_search($chars, $tele)!=false)
          return 'tele';
        return 'none';
    }
    function run_mailign_of_grades()
    {
        $date_time_array = getdate( time() );
        $day=$date_time_array['weekday'];
        $day=substr(mb_strtolower($day),0,3);
        //echo $day;
        $sql="SELECT DISTINCT student_id FROM sms_queue";
        $row_students=db_request(db_execute($sql));
        foreach($row_students as $key=>$val)
        {
            $student_id=$row_students[$key]['STUDENT_ID'];
            $parent_id=get_parent_id($student_id);
            if($parent_id!=false)
            {
            $sql_get_parent_options="SELECT * FROM sms_notification_list WHERE person_id='$parent_id' AND profile='parent'";
            //echo "parent->".$total_grades_parent."<br>";
            $row_parent=db_request(db_execute($sql_get_parent_options));
            $total_grades_parent=$row_parent[1]['TOTAL_GRADES'];
            $checkboxes=$row_parent[1]['CHECKBOXES'];
            $checkboxes=explode(",",$checkboxes);
            $assignment="";
            foreach($checkboxes as $check)
            {
                if($check=='assignment')
                {
                    $assignment=$check;
                }
            }
            if($row_parent)
            {
            if($row_parent[1]['DAY_NOTIFY']==$day || $row_parent[1]['DAY_NOTIFY']=='every')
            {
                $sql_get_phone_parent="SELECT CFIELD_".Preferences('CURENT_PARENT_SMS_FIELD')." as phone FROM students WHERE student_id='$student_id'";
                $row_parent_phone=db_request(db_execute($sql_get_phone_parent));
                $mas_r=get_grades_week($student_id,$total_grades_parent,$assignment);
                $sms_parent=$mas_r['sms'];
                $phone=$row_parent_phone[1]['PHONE'];
                if($sms_parent!='' && $phone!='')
                {
                if($row_parent[1]['TYPE']=='standart')
                {
                    $sms_service=get_current_profile();
                    switch($sms_service['name'])
                    {
                        case 'sms48':
                            //echo $sms_parent."<-parent<br/>";
                            $flag=remove_balance($student_id,$sms_service['price']);
                            if($flag==true)
                            {
                                //echo $sms_parent."<br/>";
                                send_sms48($sms_service['login'],$sms_service['pass'],$sms_service['subject'],$sms_parent,$phone);
                                remove_record_queue($mas_r['id']);
                            }
                            break;
                        case 'sms16':
                            $flag=remove_balance($student_id,$sms_service['price']);
                            if($flag==true)
                            {
                                send_sms16($phone,$sms_parent,$sms_service['login'],$sms_service['pass'],$sms_service['subject']);
                                remove_record_queue($mas_r['id']);
                            }
                            break;
                    }
                }
                elseif($row_parent[1]['TYPE']=='free')
                {
                    $provider=get_provider($phone);
                    $email="aalifirenko@ais-company.ru";
                    $res=send_free($phone,$email,$sms,$provider);
                    remove_record_queue($mas_r['id']);
                }
               }
                }
            }
           }
        }
        return '1';
  }
 function remove_record_queue($ids)
 {
     $ids=explode(",",$ids);
     foreach($ids as $id)
     {
         $sql="DELETE FROM sms_queue WHERE id='$id'";
         db_execute($sql);
     }
 }
 function notification_attendance($student_id,$code,$course_id)
 {
     if($student_id!='' && $code!='' && $course_id!='')
     {
         $sql_get_disc="SELECT c.title as title FROM course_sections as cs,courses as c WHERE cs.course_section_id='$course_id' AND cs.course_id=c.course_id";
         $row_disc=db_request(db_execute($sql_get_disc));
         if($code=='20')
         {
             $disc=$row_disc[1]['TITLE'];
             $check_name="absent";
             $sms_text=Preferences('SMS_ABSENCE_TEXT');
             $sms_text=str_replace("[date]", date('Y-m-d'), $sms_text);
             $sms_text=str_replace("[discipline]", $disc, $sms_text);
         }
         elseif($code=='21')
         {
             $disc=$row_disc[1]['TITLE'];
             $check_name="tardy";
             $sms_text=Preferences('SMS_DELAY_TEXT');
             $sms_text=str_replace("[date]", date('Y-m-d'), $sms_text);
             $sms_text=str_replace("[discipline]", $disc, $sms_text);
         }
             $sql_get_parent=db_limit("SELECT sis.address_id FROM students_in_sr as sis WHERE sis.student_id='$student_id'",1);
             $sql_get_phones="SELECT s.CFIELD_".Preferences('CURENT_STUDENT_SMS_FIELD')." as student_phone,s.CFIELD_".Preferences('CURENT_PARENT_SMS_FIELD')." as parent_phone,($sql_get_parent) as parent_id FROM students as s WHERE s.student_id='$student_id'";
             $row_phones=db_request(db_execute($sql_get_phones));
             //$phone_student=$row_phones[1]['STUDENT_PHONE'];
             $phone_parent=$row_phones[1]['PARENT_PHONE'];
             $parent_id=$row_phones[1]['PARENT_ID'];
             if($phone_parent && $parent_id)
             {
                 $sql_get_parent_options="SELECT * FROM sms_notification_list WHERE person_id='$parent_id' AND profile='parent'";
                 $row_parent=db_request(db_execute($sql_get_parent_options));
                 $type_parent=$row_parent[1]['TYPE'];
                 $checkboxes_parent=$row_parent[1]['CHECKBOXES'];
                 $checkboxes_parent=explode(",",$checkboxes_parent);
                 $flag_parent=false;
                 foreach($checkboxes_parent as $check_parent)
                 {
                     if($check_parent==$check_name)
                     {
                         $flag_parent=true;
                     }
                 }
                 if($flag_parent==true)
                 {
                     if($type_parent=='standart')
                     {
                         $profile=get_current_profile();
                        switch($profile['name'])
                        {
                            case 'sms48':
                                //echo $sms_parent."<-parent<br/>";
                                $flag=remove_balance($student_id,$sms_service['price']);
                                if($flag==true)
                                    //echo "par->".$sms_text."<br/>";
                                    send_sms48($profile['login'],$profile['pass'],$profile['subject'],$sms_text,$phone_parent);
                                break;
                            case 'sms16':
                                $flag=remove_balance($student_id,$sms_service['price']);
                                if($flag==true)
                                    send_sms16($phone_parent,$sms_text,$profile['login'],$profile['pass'],$profile['subject']);
                                break;
                        }
                     }
                     elseif($type_parent=='free')
                     {
                         $provider=get_provider($phone);
                         $email="aalifirenko@ais-company.ru";
                         $res=send_free($phone_parent,$email,$sms_text,$provider);
                     }
                 }
             }
         }
 }
 function remove_balance($student_id,$price)
 {
     $sql_get_balance="SELECT * FROM billing_student_fees WHERE student_id='".$student_id."'";
        $row_balance=db_request(db_execute($sql_get_balance));
        $stop_flag=false;
        foreach($row_balance as $num=>$tit)
        {
            if($row_balance[$num]['AMOUNT']>=$price && $stop_flag==false && $row_balance[$num]['PAIP']=='Y')
            {
                //echo "stud_balance=".$row_balance[$num4]['AMOUNT']."<br/>";
                $id_fees=$row_balance[$num]['ID'];
                $amount_fees=$row_balance[$num]['AMOUNT'];
                $stop_flag=true;
            }
        }
        if($id_fees && $amount_fees && $stop_flag==true)
        {
        $total=$amount_fees-$price;
        $total=str_replace(",", ".", $total);
        $sql_update_balance="UPDATE billing_student_fees SET amount='$total' WHERE id='$id_fees'";
        db_execute($sql_update_balance);
        }
        return $stop_flag;
 }
function get_current_profile()
{
    $sql_get_profile="SELECT * FROM sms_profiles WHERE ID='".Preferences('CURRENT_SMS_PROFILE')."'";
    $row_profile=db_request(db_execute($sql_get_profile));
    $mas['price']=$row_profile[1]['PRICE'];
    $mas['name']=$row_profile[1]['SYSTEM_NAME'];
    $mas['login']=$row_profile[1]['LOGIN'];
    $mas['pass']=$row_profile[1]['PASS'];
    $mas['subject']=$row_profile[1]['MSG_SUBJECT'];
    $mas['title']=$row_profile[1]['TITLE'];
    return $mas;
}
function clear_queue()
{
    $sql="DELETE FROM sms_queue";
    db_execute($sql);
}
function get_parent_id($student_id)
{
    $sql_get_parent_id=db_limit("SELECT sis.address_id FROM students_in_sr as sis WHERE sis.student_id='$student_id'",1);
    $sql_get_phone="SELECT s.*,($sql_get_parent_id) as parent_id FROM students as s WHERE student_id='$student_id'";
    $row=db_request(db_execute($sql_get_phone));
    $parent_id=$row[1]['PARENT_ID'];
    if(empty($parent_id))
        return false;
    return $parent_id;
}
function get_grades_week($student_id,$total_grades,$assignment)
{
        //echo "total_grade->".$total_grades."<br/>";
        $week_start_stamp = date("Y-m-d",define_week_start_and_end("start"));
        $day_end=date("d");
        //echo $day_end;
        $day_end--;
        $day_start=date("d",define_week_start_and_end("start"));
        $week_end_stamp = date("Y-m");
        $week_end_stamp.=$day_end;
        $mas_names=array(_('Mon'),_('Tue'),_('Wed'),_('Thu'),_('Fri'),_('Sat'),_('Sun'));
        $mas_replace=array(_('Mon')."()",_('Tue')."()",_('Wed')."()",_('Thu')."()",_('Fri')."()",_('Sat')."()",_('Sun')."()");
        $count=0;
        for($i=$day_start;$i<=$day_end+1;$i++)
        {
            $d=date("Y-m",define_week_start_and_end("start"))."-".$i;
            //$mas_dates[$d]=$mas_names[$count];
        //var_dump($mas_dates);
        $sql_get_discipline="SELECT DISTINCT discipline
                        FROM sms_queue
                        WHERE student_id='$student_id' AND date='$d'";
        $row_discipline=db_request(db_execute($sql_get_discipline),array(),array());
        $text_sms.=$mas_names[$count]."(";
        foreach($row_discipline as $num=>$arr)
        {
            $sql_get_grades="SELECT *
                            FROM sms_queue
                            WHERE student_id='$student_id' AND date='$d' AND discipline='".$row_discipline[$num]['DISCIPLINE']."'";
           $row_grade=db_request(db_execute($sql_get_grades));
           $ids.=$row_grade[$num]['ID'].",";
           $text_sms.=$row_discipline[$num]['DISCIPLINE'].":";
           //var_dump($row_grade);
           $grade="";
           foreach ($row_grade as $num2=>$arr2)
           {
               if($row_grade[$num2]['ESTIMATE']=='-1')
                       $row_grade[$num2]['ESTIMATE']='*';
               if($assignment!='')
               {
                   if($row_grade[$num2]['ESTIMATE']=='*')
                   {
                       $grade.=$row_grade[$num2]['ESTIMATE'].",";
                   }
               }
               else
               {
                   if(empty($total_grades))
                   {
                       $grade.=$row_grade[$num2]['ESTIMATE'].",";
                   }
                   else
                   {
                       if($row_grade[$num2]['ESTIMATE']!='*')
                       {
                           if($row_grade[$num2]['ESTIMATE']<=$total_grades)
                               $grade.=$row_grade[$num2]['ESTIMATE'].",";
                       }
                   }
                   $phone=$row_grade[$num2]['PHONE'];
               }
           }
           $grade=substr($grade,0,-1);
           $text_sms.=$grade.";";
        }
        $text_sms.=")";
        $count++;
       }
       foreach($mas_replace as $str)
       {
           $text_sms=str_replace($str, "", $text_sms);
       }
       $return_mas['phone']=$phone;
       $return_mas['sms']=$text_sms;
       $ids=substr($ids,0,-1);
       $return_mas['id']=$ids;
       return $return_mas;
 }
function define_week_start_and_end($what)
{
        $time_stamp = time();
        $cur_day = getdate($time_stamp); 
        $month_day = $cur_day['mday'];        
        $month_num = $cur_day['mon'];        
        $year_num = $cur_day['year'];        
        $day_num = $cur_day['wday'];
        if ($day_num!=0)
        {
                $week_start = $month_day-$day_num+1;
        }
        else
        {
                $week_start = $month_day-6;
        }
        $week_end = $week_start+6;
        $week_start_month_num = $month_num;
        $week_end_month_num = $month_num;
        $week_start_year_num = $year_num;
        $week_end_year_num = $year_num;
        
        if ($week_start < 1)
        {
                if ($month_num == 1)
                {
                        $week_start_year_num--;
                        $week_start_month_num = 12;
                }
                else
                {
                        $week_start_month_num--;
                }
                $last_day_in_previous_month = 31;
                while (!checkdate ($week_start_month_num, $last_day_in_previous_month, $week_start_year_num))
                {
                        $last_day_in_previous_month--;
                }
                $week_start += $last_day_in_previous_month;
        }
        $last_day_in_month = 31;
        while (!checkdate ($week_start_month_num, $last_day_in_month, $week_start_year_num))
        {
                $last_day_in_month--;
        }
        if ($week_end > $last_day_in_month)
        {
                if ($month_num == 12)
                {
                        $week_end_year_num++;
                        $week_end_month_num = 1;
                }
                else
                {
                        $week_end_month_num++;
                }
                $week_end = $week_end-$last_day_in_month;
        }

        $week_start_time_stamp = gmmktime (0, 0, 0, $week_start_month_num, $week_start, $week_start_year_num);
        $week_end_time_stamp = gmmktime (23, 59, 59,  $week_end_month_num, $week_end, $week_end_year_num);
        if ($what == "start")
        {
                return $week_start_time_stamp;
        }
        else if ($what == "end")
        {
                return $week_end_time_stamp;
        }
        return NULL;
}
?>