phpBMS

root/trunk/phpbms/include/session.php

Revision 767, 21.3 KB (checked in by brieb, 2 years ago)
  • Turned off all warnings and errors when not in debug mode. This is for security purposes so that the absolute path is not exposed.
  • fixed AR run aging to properly print checked print outs
  • Added code to grab the deafult time zone and set it. This will help stem problems from E_STRICT reporting and also should speed up some date/time functions.
  • Fixed line item to sales order relationships for new installs
  • Property svn:keywords set to LastChangedBy LastChangedDate LastChangedRevision
Line 
1<?php
2/*
3 $Rev$ | $LastChangedBy$
4 $LastChangedDate$
5 +-------------------------------------------------------------------------+
6 | Copyright (c) 2004 - 2010, Kreotek LLC                                  |
7 | All rights reserved.                                                    |
8 +-------------------------------------------------------------------------+
9 |                                                                         |
10 | Redistribution and use in source and binary forms, with or without      |
11 | modification, are permitted provided that the following conditions are  |
12 | met:                                                                    |
13 |                                                                         |
14 | - Redistributions of source code must retain the above copyright        |
15 |   notice, this list of conditions and the following disclaimer.         |
16 |                                                                         |
17 | - Redistributions in binary form must reproduce the above copyright     |
18 |   notice, this list of conditions and the following disclaimer in the   |
19 |   documentation and/or other materials provided with the distribution.  |
20 |                                                                         |
21 | - Neither the name of Kreotek LLC nor the names of its contributore may |
22 |   be used to endorse or promote products derived from this software     |
23 |   without specific prior written permission.                            |
24 |                                                                         |
25 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS     |
26 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT       |
27 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A |
28 | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT      |
29 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,   |
30 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT        |
31 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,   |
32 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY   |
33 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT     |
34 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE   |
35 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.    |
36 |                                                                         |
37 +-------------------------------------------------------------------------+
38*/
39
40/**
41 * Turn on/or off debugging
42 */
43@ define("APP_DEBUG", true);
44if(APP_DEBUG)
45    error_reporting(E_ALL);
46else
47    error_reporting(0);
48
49/**
50 * Until we instatiate time zone in the program
51 * This lines suppress warnings when error reporting is strict
52 */
53@ date_default_timezone_set(date_default_timezone_get());
54
55// Error Class - This class reports errors.  It can also log these errors
56// to the phpBMS log table in some cases.
57class appError{
58
59        var $number=0;
60        var $title="";
61        var $details="";
62        var $stop=true;
63        var $logerror=true;
64        var $format="xhtml";
65        var $backtrace = array();
66
67        //init
68        function appError($number=0,$details="",$title="",$display=false,$stop=true,$logerror=true,$format="xhtml"){
69
70                $this->title = $title;
71                $this->details = $details;
72                $this->stop = $stop;
73
74                $this->logerror = $logerror;
75                $this->format = $format;
76                $this->number = $number;
77
78                // find a predetermined title;
79                if($this->number<0){
80
81                        switch($number){
82                                case -300:
83                                        $this->title = "settings.php file not readable";
84                                        $this->details =
85                                        'If this is the initial installation of the program,
86                                        you may wan to run the installer.  Use your web browser to navigate to:<br /><br />
87
88                                        <a href="'.APP_PATH.'install">phpBMS Installation</a><br /><br />
89
90                                        If your application already has a settings.php file in the main phpbms directory, you may need to give your web server rights to read the file.';
91                                        break;
92                                case -400:
93                                case -410:
94                                case -420:
95                                case -430:
96                                case -440:
97                                case -450:
98                                case -460:
99                                        $this->title="Database Error";
100                                        break;
101                        }//end case;
102
103                }//endif this->number
104
105                $this->backtrace = debug_backtrace();
106
107                if(count($this->backtrace) > 1)
108                    array_shift($this->backtrace);
109
110                if($display || APP_DEBUG) $this->display($format);
111                if($logerror) $this->logError();
112                if($this->stop) exit;
113
114        }//eend function init
115
116
117        //This function outputs the error to screen either in
118        // XHTML, plain text, or JSON format
119        function display($format = NULL){
120
121                if($format == NULL)
122                        $format = $this->format;
123
124                switch(strtolower($format)){
125
126                        case "json":
127
128                                $return["id"] = $this->number;
129                                $return["title"] = $this->title;
130                                $return["details"] = $this->details;
131
132                                echo json_encode($return);
133
134                                break;
135
136                        case "xhtml":
137
138                                // Unsure if this line is needed, as it limits what we can do with detail print out
139                                //$this->details = str_replace("\n","<br />", htmlspecialchars($this->details,ENT_COMPAT,"UTF-8"));
140
141                                if(defined("APP_PATH")){
142
143                                        if(!defined("STYLESHEET"))
144                                                define("STYLESHEET","mozilla");
145
146                                        ?><link href="<?php echo APP_PATH ?>common/stylesheet/<?php echo STYLESHEET ?>/base.css" rel="stylesheet" type="text/css" /><?php
147
148                                } else {
149
150                                        //if the app_path is not defined, we can try including the mozilla stylesheet, relative to
151                                        // the assumed phpbms root
152                                        ?><link href="common/stylesheet/mozilla/base.css" rel="stylesheet" type="text/css" /><?php
153
154                                }//end if
155
156                                ?><div class="bodyline">
157                                        <h1><span>phpBMS Error: <?php echo $this->number; if($this->title) echo " ".$this->title?></span></h1>
158                                        <?php if($this->details) {?>
159                                        <div class="box">
160                                                <?php echo $this->details?>
161                                        </div>
162                                        <?php  } //end if
163                                        if(count($this->backtrace) && APP_DEBUG){
164
165                                            ?>
166                                            <ul class="notes">
167                                                <?php foreach($this->backtrace as $trace){
168
169                                                    ?>
170                                                    <li>
171                                                        <strong>
172                                                        <?php
173                                                            if(isset($trace["class"]))
174                                                                echo $trace["class"]."-&gt;";
175
176                                                            if(isset($trace["function"]))
177                                                                echo $trace["function"];
178                                                        ?>
179                                                        </strong>
180                                                        in <?php echo $trace["file"] ?>
181                                                        on line <?php echo $trace["line"] ?>
182                                                    </li>
183                                                    <?php
184
185                                                }//end while ?>
186                                            </ul>
187                                            <?php
188
189                                        }//endif ?>
190                                </div><?php
191
192                                break;
193
194                        default:
195
196                                echo "phpBMS Error: ".$this->number;
197                                if($this->title) echo ": ".$this->title;
198                                if($this->details) echo  " - ".$this->details;
199
200                                if(count($this->backtrace) && APP_DEBUG){
201
202                                    echo "\n";
203
204                                    foreach($this->backtrace as $trace){
205
206                                        if(isset($trace["class"]))
207                                            echo $trace["class"]."->";
208
209                                        if(isset($trace["function"]))
210                                            echo $trace["function"];
211
212                                        echo " in ".$trace["file"];
213                                        echo " on line ".$trace["line"];
214
215                                    }//end while
216
217                                }//endif
218
219                                break;
220                }//end switch
221        }// end dispaly function
222
223
224        // this function logs the error in the phpBMS log table
225        function logError(){
226
227                $message = $_SERVER["REQUEST_URI"]."\n";
228                $message .= $this->number;
229
230                if($this->title)
231                        $message.=": ".$this->title;
232
233                if($this->details)
234                        $message.="\n\n".$this->details;
235
236                $log = new phpbmsLog($message,"ERROR");
237
238        }//end logError
239
240}//end appError class
241
242
243// This is the class for logging items tot the phpBMS
244// log table;
245class phpbmsLog{
246
247        var $db = NULL;
248        var $type = "ERROR";
249        var $value = "";
250
251        /**
252          *   $userid
253          *   @var string user's uuid
254          */
255        var $userid = "usr:cb67a60b-a264-735c-6189-49a7c883af0b";
256
257        function phpbmsLog($value=NULL,$type=NULL,$userid=NULL,$db=NULL,$sendLog=true){
258
259                //in most cases, it is prudent for the log object to have it's own DB object
260                // so that it can properly supress errors without goofing things up.
261                if($db){
262                        if(is_object($db)){
263
264                                $this->db = $db;
265
266                                $this->db->showError=false;
267                                $this->db->logError=false;
268                                $this->db->stopOnError=false;
269
270                        }//endif object
271
272                } else {
273
274                        if(class_exists("db")){
275
276                                $this->db= new db(false);
277
278                                $this->db->showError=false;
279                                $this->db->logError=false;
280                                $this->db->stopOnError=false;
281
282                                $this->db->connect();
283                                $this->db->selectSchema();
284
285                        } else
286                                return false;
287
288                }//endif db
289
290                if($value)
291                        $this->value = $value;
292
293                if($type)
294                        $this->type = $type;
295
296                if($userid)
297                        $this->userid = $userid;
298
299                if($sendLog)
300                        return $this->sendLog();
301                else
302                        return true;
303
304        }//end function init
305
306
307        // inserts record into log table
308        function sendLog(){
309
310                $ip = $_SERVER["REMOTE_ADDR"];
311
312                $insertstatement = "
313                        INSERT INTO
314                                `log`
315                        (`type`, `value`, `userid`, `ip`) VALUES (
316                                '".mysql_real_escape_string($this->type)."',
317                                '".mysql_real_escape_string($this->value)."',
318                                '".mysql_real_escape_string($this->userid)."',
319                                '".$ip."'
320                        )";
321
322                $this->db->query($insertstatement);
323
324        }//end function sendLog
325
326}//end class phpbmslog
327
328
329// This class handles the loading of the database, session and application
330// variables, as well as verifying API level logins
331class phpbmsSession{
332
333        var $db = null;
334
335        function loadDBSettings($reportError = true){
336
337                // This functions looks for the settings.php file, and loads
338                // the database variables as constants.  As an added benefit
339                // it adds the phpBMS root as an included path.
340
341
342                //need to look for settings file... only go up a total of 10 directories
343                $currdirectory = getcwd();
344
345                //Prep the setting of the application path;
346                $currentURL = explode("/",$_SERVER["PHP_SELF"]);
347                array_pop($currentURL);
348
349                $count = 0;
350                $path = "";
351
352                //We need to find the applications root
353                while(!file_exists("phpbmsversion.php") && $count < 9){
354
355                        $path.="../";
356                        @ chdir("../");
357                        $count++;
358
359                }//end while
360
361                //Now set the Web location (APP_PATH)
362                $appPath = "/";
363                for($i = 0; $i < count($currentURL) - $count; $i++)
364                        if($currentURL[$i])
365                                $appPath .= $currentURL[$i]."/";
366
367                define("APP_PATH", $appPath);
368
369                $settingsfile =  @ fopen("settings.php","r");
370
371                if($settingsfile){
372
373                        //loop through the settings file and load variables into the session
374                        while( !feof($settingsfile)) {
375
376                                $line = NULL;
377                                $key = NULL;
378                                $value = NULL;
379                                $line = @ fscanf($settingsfile,"%[^=]=%[^[]]",$key,$value);
380
381                                if ($line){
382
383                                        $key=trim($key);
384                                        $value=trim($value);
385
386                                        if($key!="" and !strpos($key,"]")){
387
388                                                $startpos=strpos($value,"\"");
389                                                $endpos=strrpos($value,"\"");
390
391                                                if($endpos!=false)
392                                                        $value=substr($value,$startpos+1,$endpos-$startpos-1);
393
394                                                if(strpos($key,"mysql_")===0)
395                                                        define(strtoupper($key),$value);
396
397                                        }//endif key
398
399                                }//endif line
400
401                        }//endwhile
402
403                        @ fclose($settingsfile);
404
405                        //For legacy installations where pconnect is not set
406                        if(!defined("MYSQL_PCONNECT"))
407                                define("MYSQL_CONNECT",true);
408
409                        //this adds the phpbms root to the include path
410                        if ( !defined( "PATH_SEPARATOR" ) ) {
411
412                                //if we cannot determin the OS, we will assume its unix
413                                if(!isset($_ENV["OS"]))
414                                        $_ENV["OS"] = "unix";
415
416                                if ( strpos( $_ENV["OS"], "Win" ) !== false )
417                                        define( "PATH_SEPARATOR", ";" );
418                                else
419                                        define( "PATH_SEPARATOR", ":" );
420
421                        }//end if
422
423                        $pathToAdd = @ getcwd();
424
425                        //Now we include the root application path to php's include path
426                        if(ini_set("include_path", ini_get("include_path").PATH_SEPARATOR.$pathToAdd) === false && $reportError)
427                                $error = new appError(-310, "Your implementation of PHP does not allow changing of the include path. You may need to modify your PHP settings to allow phpBMS to modify this php ini setting. If you are using a web hosting company, you may need to contact them to allow this.", "Cannot add to include path", true, true, false);
428
429
430                        //return directory to current directory
431                        @ chdir ($currdirectory);
432
433                        return $path;
434
435                } else {
436
437                        if($reportError)
438                                $error = new appError(-300,"","",true,true,false);
439
440                        return false;
441
442                }//endif settingsfile
443
444        }//end function
445
446
447        function loadSettings($encoding = "utf8"){
448
449                // We are going to make sure that we are using utf8
450                // but it works only in mySQL 5, so we supress errors
451                // when trying it.
452                if($this->db==NULL)
453                        $error=new appError(-310,"","Database not loaded");
454
455                $this->db->logError = false;
456                $this->db->stopOnError = false;
457
458                $this->db->setEncoding($encoding);
459
460                $this->db->logError = true;
461
462                $querystatement = "SELECT name,value FROM settings";
463
464                $queryresult = $this->db->query($querystatement);
465
466                if(!$queryresult){
467
468                        $error= new appError(-310,"If you have not ran the update script for phpBMS, please run it before logging in.","Could Not Retrieve Settings From Database");
469                        return false;
470
471                } else {
472
473                        while($therecord=$this->db->fetchArray($queryresult)){
474
475                                //old versions used a reserved constant in certain php versions
476                                if($therecord["name"] == "currency_symbol")
477                                        $therecord["name"] = "currency_sym";
478
479                                if(!defined(strtoupper($therecord["name"])))
480                                        define(strtoupper($therecord["name"]),$therecord["value"]);
481                        }//end while
482
483
484                        /**
485                          *  Need to load the ENCRYPTION_KEY if it is called for.
486                          */
487
488                        if(defined("ENCRYPTION_KEY_PATH"))
489                                if(is_file(ENCRYPTION_KEY_PATH)){
490
491                                        $res = @ fopen(ENCRYPTION_KEY_PATH, "r");
492
493                                        if($res !== false){
494
495                                            if(@filesize(ENCRYPTION_KEY_PATH))
496                                                define("ENCRYPTION_KEY",trim(fread($res, filesize(ENCRYPTION_KEY_PATH))));
497                                            else
498                                                $error = new appError(-230, "Cannot open path '".ENCRYPTION_KEY_PATH."' or file has zero length ", "Invalid Encryption Key File", true, true);
499
500                                        } elseif(ENCRYPT_PAYMENT_FIELDS){
501
502                                            $error = new appError(-229, "Invalid encryption file or cannot open '".ENCRYPTION_KEY_PATH."'", "Invalid Encryption Key File", true, true);
503
504                                        }else{
505
506                                            define("ENCRYPTION_KEY", "");
507
508                                        }//end if
509
510                                }elseif(ENCRYPT_PAYMENT_FIELDS)
511                                    $error = new appError(-228, ENCRYPTION_KEY_PATH." missing or invalid.", "Cannot Open Encryption Key File", true, true);
512                                else
513                                    define("ENCRYPTION_KEY", "");
514
515                        // This following code is for windows boxen, because they lack some server varables as well
516                        // formating options for the strftime function
517                        if(!isset($_SERVER['REQUEST_URI'])) {
518                                $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'];
519
520                                if(!defined("HOUR_FORMAT"))
521                                        define("HOUR_FORMAT","%I");
522
523                                // Append the query string if it exists and isn't null
524                                if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING']))
525                                        $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
526                        } else
527                                if(!defined("HOUR_FORMAT"))
528                                        define("HOUR_FORMAT","%l");
529
530                        return true;
531
532                }//endif queryresult
533
534        }//end function
535
536
537        // This is in a function in case we want to do sessions differently in the future
538        function startSession(){
539
540                session_name("phpBMS".preg_replace('/\W/',"",APPLICATION_NAME)."v096ID");
541                session_start();
542
543        }//end function startSesion
544
545
546
547        /**
548         * Verifies login credentials from an API
549         *
550         * This functions verifies credentials for API (portal access) user.
551         *
552         * @param string $user user name
553         * @param string $pass password
554         * @param string $format format to send errors back in, currently supports 'json' (default) and 'xhtml'
555         *
556         */
557        function verifyAPIlogin($user, $pass, $format = "json"){
558
559            $thereturn = false;
560            $this->db->stopOnError = false;
561
562            $querystatement = "
563                SELECT
564                    id,
565                    firstname,
566                    lastname,
567                    email,
568                    phone,
569                    department,
570                    employeenumber,
571                    admin
572                FROM
573                    users
574                WHERE
575                login != 'Scheduler'
576                    AND login = '".mysql_real_escape_string($user)."'
577                    AND password = ENCODE('".mysql_real_escape_string($pass)."', '".mysql_real_escape_string(ENCRYPTION_SEED)."')
578                    AND revoked = 0
579                    AND portalaccess = 1";
580
581            $queryresult = $this->db->query($querystatement);
582
583            if(!$queryresult) {
584
585                $error = new appError(-720,"","Error retrieving user record",true,true,true,$format);
586                return false;
587
588            }//endif
589
590            if($this->db->numRows($queryresult)){
591
592                //We found a record that matches in the database
593                // populate the session and go in
594                $_SESSION["userinfo"] = $this->db->fetchArray($queryresult);
595
596                $querystatement = "
597                    UPDATE
598                        users
599                    SET
600                        modifieddate = modifieddate,
601                        lastlogin = NOW()
602                    WHERE
603                        id = ".$_SESSION["userinfo"]["id"];
604
605                $queryresult = @ $this->db->query($querystatement);
606
607                if(!$queryresult)
608                    $error = new appError(-730, "", "Error Updating User Login Time", true, true, true, $format);
609                else
610                    $thereturn = true;
611
612            }//endif numrows
613
614            return $thereturn;
615
616        }//end function verifyAPIlogin
617
618
619        //Check to see if install folders are present.  If so, do not continue.
620        function checkForInstallDirs($errorFormat = "xhtml"){
621
622                //first lets check for the main programs install folder
623                if(file_exists("install") && is_dir("install"))
624                        $error = new appError(-353,"You must remove the install directory and all modules' install directories before phpBMS can run.","Main Install Directory Present",true,true,true,$errorFormat);
625
626                if(file_exists("modules") && is_dir("modules")){
627
628                        $thedir = @ opendir("modules");
629
630                        while($entry = readdir($thedir)){
631
632                                if($entry != "." && $entry != ".." && $entry != "base" && $entry != "sample" && is_dir("modules/".$entry)){
633
634                                        if(file_exists("modules/".$entry."/install") && is_dir("modules/".$entry."/install")){
635
636                                                $error = new appError(-354,"You must remove the install directory and all modules' install directories before phpBMS can run.","Module '".$entry."' Install Directory Present",true,true,true,$errorFormat);
637
638                                        }//endif
639
640                                }//endif
641
642                        }//end while
643
644                }//end if
645
646        }//end function checkForInstallDirs
647
648}//end phpbmsSession class
649
650
651
652// Start Login verification Code
653//==============================================================================
654if(!isset($sqlEncoding))
655        $sqlEncoding = "utf8";
656
657if(!defined("noStartup")){
658
659        $scriptname = basename($_SERVER["PHP_SELF"]);
660        $phpbmsSession = new phpbmsSession;
661
662        //Testing for API login
663        if(strpos($scriptname,"api_")!==false){
664
665                if(!isset($_POST["phpbmsformat"]))
666                        $_POST["phpbmsformat"] = "json";
667
668                if(isset($_POST["phpbmsusername"]) && isset($_POST["phpbmspassword"])){
669
670                        $phpbmsSession->loadDBSettings(APP_DEBUG);
671
672                        if(!APP_DEBUG)
673                                $phpbmsSession->checkForInstallDirs("json");
674
675                        include_once("include/db.php");
676                        $db = new db();
677                        $phpbmsSession->db = $db;
678
679                        include_once("common_functions.php");
680                        $phpbmsSession->loadSettings($sqlEncoding);
681                        $phpbms = new phpbms($db);
682
683
684                        if(!$phpbmsSession->verifyAPILogin($_POST["phpbmsusername"],$_POST["phpbmspassword"], $_POST["phpbmsformat"]))
685                                $error = new appError(-700,"","Login credentials incorrect",true,true,true,"json");
686
687                } else
688                    $error= new appError(-710, "", "No login credentials passed", true, true, true, $_POST["phpbmsformat"]);
689
690        } else {
691
692                $phpbmsSession->loadDBSettings(APP_DEBUG);
693
694                if(!APP_DEBUG)
695                        $phpbmsSession->checkForInstallDirs();
696
697                //start database
698                include_once("include/db.php");
699                $db = new db();
700
701                $phpbmsSession->db = $db;
702
703                //load application settings from table
704                $phpbmsSession->loadSettings($sqlEncoding);
705
706                include_once("common_functions.php");
707                $phpbms = new phpbms($db);
708
709                if(!isset($noSession))
710                        $phpbmsSession->startSession();
711
712                if (!isset($_SESSION["userinfo"]) && $scriptname != "index.php") {
713
714                        if(isset($loginNoKick)){
715
716                                if(!isset($loginNoDisplayError))
717                                        exit();
718
719                        } else{
720
721                                goURL(APP_PATH."index.php");
722
723                        }//endif
724
725                }//endif iseet userinfo
726
727        }//endif
728
729        $db->stopOnError = true;
730
731}//end if
732
733?>
Note: See TracBrowser for help on using the browser.
Scanned by Orvant Copyright © 2010 Kreotek, LLC. All Rights reserved.