root/trunk/owa_lib.php

Revision 558, 20.1 kB (checked in by padams, 3 days ago)

fixed several bugs in serviceUser
renamed 'Administrator' role to 'admin' to maintain backwards compatability
fixed bogus error msg when applying module updates successfully

Line 
1<?php
2
3//
4// Open Web Analytics - An Open Source Web Analytics Framework
5//
6// Copyright 2006 Peter Adams. All rights reserved.
7//
8// Licensed under GPL v2.0 http://www.gnu.org/copyleft/gpl.html
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16// $Id$
17//
18
19require_once 'owa_env.php';
20require_once(OWA_PEARLOG_DIR . '/Log.php');
21require_once(OWA_INCLUDE_DIR.'/class.inputfilter.php');
22//require_once(OWA_BASE_CLASS_DIR.'settings.php');
23
24/**
25 * Utility Functions
26 *
27 * @author      Peter Adams <peter@openwebanalytics.com>
28 * @copyright   Copyright &copy; 2006 Peter Adams <peter@openwebanalytics.com>
29 * @license     http://www.gnu.org/copyleft/gpl.html GPL v2.0
30 * @category    owa
31 * @package     owa
32 * @version             $Revision$           
33 * @since               owa 1.0.0
34 */
35class owa_lib {
36
37        /**
38         * Convert Associative Array to String
39         *
40         * @param string $inner_glue
41         * @param string $outer_glue
42         * @param array $array
43         * @return string
44         */
45        function implode_assoc($inner_glue, $outer_glue, $array) {
46           $output = array();
47           foreach( $array as $key => $item ) {
48                          $output[] = $key . $inner_glue . $item;
49                }
50               
51                return implode($outer_glue, $output);
52        }
53                       
54        /**
55         * Deconstruct Associative Array
56         *
57         * For example this takes array([1] => array(a => dog, b => cat), [2] => array(a => sheep, b => goat))
58         * and tunrs it into array([a] => array(dog, sheep), [b] => array(cat, goat))
59         *
60         * @param array $a_array
61         * @return array $data_arrays
62         * @access public
63         */
64        function deconstruct_assoc($a_array) {
65                if (!empty($a_array)):
66               
67                        $data_arrays = array();
68               
69                        if(!empty($a_array[1])) :
70                       
71                                foreach ($a_array as $key => $value) {
72                                        foreach ($value as $k => $v) {
73                                                $data_arrays[$k][] = $v;
74                               
75                                        }
76                                }
77                        else:
78                                //print_r($a_array[0]);
79                                foreach ($a_array[0] as $key => $value) {
80                                        $data_arrays[$key][] = $value;
81                                }
82                        endif;
83                       
84                        return $data_arrays;
85                else:
86                        return array();
87                endif;
88        }
89       
90       
91        function decon_assoc($a_array) {
92               
93                $data_arrays = array();
94       
95                foreach ($a_array as $key => $value) {
96                        //foreach ($value as $k => $v) {
97                                $data_arrays[$key][] = $value;
98               
99                        //}
100                }
101               
102                return $data_arrays;
103        }
104
105        // php 4 compatible function
106        function array_intersect_key() {
107       
108        $arrs = func_get_args();
109        $result = array_shift($arrs);
110        foreach ($arrs as $array) {
111            foreach ($result as $key => $v) {
112                if (!array_key_exists($key, $array)) {
113                    unset($result[$key]);
114                }
115            }
116        }
117        return $result;
118     }
119       
120        // php4 compatible function
121        function array_walk_recursive(&$input, $funcname, $userdata = "")
122    {
123        if (!is_callable($funcname))
124        {
125            return false;
126        }
127       
128        if (!is_array($input))
129        {
130            return false;
131        }
132       
133        if (is_array($funcname))
134        {
135            $funcname = $funcname[0].'::'.$funcname[1];
136        }
137       
138       
139        foreach ($input AS $key => $value)
140        {
141            if (is_array($input[$key]))
142            {
143                array_walk_recursive($input[$key], $funcname, $userdata);
144            }
145            else
146            {
147                $saved_value = $value;
148                if (!empty($userdata))
149                {
150                    $funcname($value, $key, $userdata);
151                }
152                else
153                {
154                    $funcname($value, $key);
155                }
156               
157                if ($value != $saved_value)
158                {
159                    $input[$key] = $value;
160                }
161            }
162        }
163        return true;
164    }
165
166        /**
167         * Array of Current Time
168         *
169         * @return array
170         * @access public
171         */
172        function time_now() {
173               
174                $timestamp = time();
175               
176                return array(
177                       
178                                'year'                          => date("Y", $timestamp),
179                                'month'                         => date("n", $timestamp),
180                                'day'                           => date("d", $timestamp),
181                                'dayofweek'             => date("w", $timestamp),
182                                'dayofyear'             => date("z", $timestamp),
183                                'weekofyear'            => date("W", $timestamp),
184                                'hour'                          => date("G", $timestamp),
185                                'minute'                        => date("i", $timestamp),
186                                'second'                        => date("s", $timestamp),
187                                'timestamp'                     => $timestamp
188                        );
189        }
190               
191        /**
192         * Error Handler
193         *
194         * @param string $msg
195         * @access public
196         */
197        function errorHandler($msg) {
198               
199                $conf = array('mode' => 0755, 'timeFormat' => '%X %x');
200                $error_logger = &Log::singleton('file', $this->config['error_log_file'], 'ident', $conf);
201                $this->error_logger->_lineFormat = '[%3$s]';
202               
203                return;
204        }
205       
206        /**
207         * Information array for Months in the year.
208         *
209         * @return array
210         */
211        function months() {
212               
213                return array(
214                                       
215                                        1 => array('label' => 'January'),
216                                        2 => array('label' => 'February'),
217                                        3 => array('label' => 'March'),
218                                        4 => array('label' => 'April'),
219                                        5 => array('label' => 'May'),
220                                        6 => array('label' => 'June'),
221                                        7 => array('label' => 'July'),
222                                        8 => array('label' => 'August'),                               
223                                        9 => array('label' => 'September'),
224                                        10 => array('label' => 'October'),
225                                        11 => array('label' => 'November'),
226                                        12 => array('label' => 'December')
227                );
228               
229        }
230       
231        function days() {
232               
233                return array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 
234                                        15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31);
235        }
236       
237        function years() {
238               
239                static $years;
240               
241                if (empty($years)):
242                       
243                        $start_year = 2005;
244                       
245                        $years = array($start_year);
246                       
247                        $num_years =  date("Y", time()) - $start_year;
248                       
249                        for($i=1; $i<=$num_years; $i++) {
250                       
251                                $years[] = $start_year + $i;
252                        }
253                       
254                        $years = array_reverse($years);
255               
256                endif;
257               
258                return $years;
259        }
260       
261       
262        /**
263         * Returns a label from an array of months
264         *
265         * @param int $month
266         * @return string
267         */
268        function get_month_label($month) {
269               
270                static $months;
271               
272                if (empty($months)):
273
274                        $months = owa_lib::months();
275               
276                endif; 
277               
278                return $months[$month]['label'];
279               
280        }
281       
282       
283        /**
284         * Sets the suffix for Days used in Date labels
285         * @depricated
286         * @param string $day
287         * @return string
288         */
289        function setDaySuffix($day) {
290               
291                switch ($day) {
292                       
293                        case "1":
294                                $day_suffix = 'st';
295                                break;
296                        case "2":
297                                $day_suffix = 'nd';
298                                break;
299                        case "3":
300                                $day_suffix = 'rd';
301                                break;
302                        default:
303                                $day_suffix = 'th';
304                }
305               
306                return $day_suffix;
307               
308        }
309       
310        /**
311         * Generates the label for a date
312         * @depricated
313         * @param array $params
314         * @return string
315         */
316        function getDatelabel($params) {
317               
318                switch ($params['period']) {
319               
320                        case "day":
321                                return sprintf("%s, %d%s %s",
322                                                        owa_lib::get_month_label($params['month']),
323                                                        $params['day'],
324                                                        owa_lib::setDaySuffix($params['day']),
325                                                        $params['year']                         
326                                                );
327                                break;
328                       
329                        case "month":
330                                return sprintf("%s %s",
331                                                        owa_lib::get_month_label($params['month']),
332                                                        $params['year']                         
333                                                );
334                                break;
335                       
336                        case "year":   
337                                return sprintf("%s",
338                                                        $params['year']                         
339                                                );
340                                break;
341                        case "date_range":
342                                return sprintf("%s, %d%s %s - %s, %d%s %s",
343                                                        owa_lib::get_month_label($params['month']),
344                                                        $params['day'],
345                                                        owa_lib::setDaySuffix($params['day']),
346                                                        $params['year'],
347                                                        owa_lib::get_month_label($params['month2']),
348                                                        $params['day2'],
349                                                        owa_lib::setDaySuffix($params['day2']),
350                                                        $params['year2']                                       
351                                                );
352                                break;
353                }
354               
355                return false;
356               
357        }
358       
359        /**
360         * Array of Reporting Periods
361         * @depricated
362         * @return array
363         */
364        function reporting_periods() {
365               
366                return array(
367                                       
368                                        'today' => array('label' => 'Today'),
369                                        'yesterday' => array('label' => 'Yesterday'),
370                                        'this_week' => array('label' => 'This Week'),
371                                        'this_month' => array('label' => 'This Month'),
372                                        'this_year' => array('label' => 'This Year'),
373                                        'last_week'  => array('label' => 'Last Week'),
374                                        'last_month' => array('label' => 'Last Month'),
375                                        'last_year' => array('label' => 'Last Year'),
376                                        'last_half_hour' => array('label' => 'The Last 30 Minutes'),                           
377                                        'last_hour' => array('label' => 'Last Hour'),
378                                        'last_24_hours' => array('label' => 'The Last 24 Hours'),
379                                        'last_seven_days' => array('label' => 'The Last Seven Days'),
380                                        'last_thirty_days' => array('label' => 'The Last Thirty Days'),
381                                        'same_day_last_week' => array('label' => 'Same Day last Week'),
382                                        'same_week_last_year' => array('label' => 'Same Week Last Year'),
383                                        'same_month_last_year' => array('label' => 'Same Month Last Year'),
384                                        'date_range' => array('label' => 'Date Range')
385                );
386               
387        }
388       
389        /**
390         * Array of Date specific Reporting Periods
391         * @depricated
392         * @return array
393         */
394        function date_reporting_periods() {
395               
396                return array(
397                                       
398                                        'day' => array('label' => 'Day'),
399                                        'month' => array('label' => 'Month'),
400                                        'year' => array('label' => 'Year'),
401                                        'date_range' => array('label' => 'Date Range')
402                );
403               
404        }
405       
406        /**
407         * Gets label for a particular reporting period
408         *
409         * @param unknown_type $period
410         * @return unknown
411         */
412        function get_period_label($period) {
413       
414                $periods = owa_lib::reporting_periods();
415               
416                return $periods[$period]['label'];
417        }
418       
419        /**
420         * Assembles the current URL from request params
421         *
422         * @return string
423         */
424        function get_current_url() {
425               
426                $url = 'http'; 
427               
428                if($_SERVER['HTTPS']=='on'):
429                        $url.= 's';
430                endif;
431               
432                $url .= '://'.$_SERVER['SERVER_NAME'];
433               
434                if($_SERVER['SERVER_PORT'] != 80):
435                        $url .= ':'.$_SERVER['SERVER_PORT'];
436                endif;
437               
438                $url .= $_SERVER['REQUEST_URI'];
439               
440                return $url;
441        }
442       
443        function inputFilter($array) {
444               
445                $f = new InputFilter;
446               
447                return $f->process($array);
448               
449        }
450       
451        /**
452         * Generic Factory method
453         *
454         * @param string $class_dir
455         * @param string $class_prefix
456         * @param string $class_name
457         * @param array $conf
458         * @return object
459         */
460        function &factory($class_dir, $class_prefix, $class_name, $conf = array(), $class_suffix = '') {
461               
462        //$class_dir = strtolower($class_dir).DIRECTORY_SEPARATOR;
463        $class_dir = $class_dir.DIRECTORY_SEPARATOR;
464        $classfile = $class_dir . $class_name . '.php';
465                $class = $class_prefix . $class_name . $class_suffix;
466               
467        /*
468         * Attempt to include a version of the named class, but don't treat
469         * a failure as fatal.  The caller may have already included their own
470         * version of the named class.
471         */
472        if (!class_exists($class)):
473            include_once $classfile;
474        endif;
475
476        /* If the class exists, return a new instance of it. */
477        if (class_exists($class)):
478            $obj = &new $class($conf);
479            return $obj;
480        endif;
481
482        $null = null;
483        return $null;
484    }
485       
486    /**
487     * Generic Object Singleton
488     *
489     * @param string $class_dir
490     * @param string $class_prefix
491     * @param string $class_name
492     * @param array $conf
493     * @return object
494     */
495    function &singleton($class_dir, $class_prefix, $class_name, $conf = array()) {
496       
497        static $instance;
498       
499        if (!isset($instance)):
500                // below missing a reference becasue the static vriable can not handle a reference
501                $instance = owa_lib::factory($class_dir, $class_prefix, $class_name, $conf = array());
502        endif;
503       
504        return $instance;
505    }
506   
507    /**
508     * 302 HTTP redirect the user to a new url
509     *
510     * @param string $url
511     */
512    function redirectBrowser($url) {
513       
514        //ob_clean();
515            // 302 redirect to URL
516                header ('Location: '.$url, true);
517                header ('HTTP/1.0 302 Found', true);
518                return;
519    }
520       
521        function makeLinkQueryString($query_params) {
522               
523                $new_query_params = array();
524               
525                //Load params passed by caller
526                if (!empty($this->caller_params)):
527                        foreach ($this->caller_params as $name => $value) {
528                                if (!empty($value)):
529                                        $new_query_params[$name] = $value;     
530                                endif;
531                        }
532                endif;
533
534                // Load overrides
535                if (!empty($query_params)):
536                        foreach ($query_params as $name => $value) {
537                                if (!empty($value)):
538                                        $new_query_params[$name] = $value;     
539                                endif;
540                        }
541                endif;
542               
543                // Construct GET request
544                if (!empty($new_query_params)):
545                        foreach ($new_query_params as $name => $value) {
546                                if (!empty($value)):
547                                        $get .= $name . "=" . $value . "&";     
548                                endif;
549                        }
550                endif;
551               
552                return $get;
553               
554        }
555       
556        function getRequestParams() {
557               
558                // Clean Input arrays
559                $params = owa_lib::inputFilter($_REQUEST);
560               
561                return owa_lib::stripParams($params);
562        }
563       
564        function stripParams($params) {
565               
566               
567                $c = &owa_coreAPI::configSingleton();
568                $config = $c->fetch('base');
569               
570                $striped_params = array();
571               
572                $len = strlen($config['ns']);
573               
574                foreach ($params as $n => $v) {
575                       
576                        // if namespace is present in param
577                        if (strstr($n, $config['ns'])):
578                                // strip the namespace value
579                                $striped_n = substr($n, $len); 
580                                //add to striped array
581                                $striped_params[$striped_n] = $v;
582                               
583                        endif;
584                       
585                }
586               
587                return $striped_params;
588               
589        }
590       
591        /**
592         * module specific require method
593         *
594         * @param unknown_type $module
595         * @param unknown_type $file
596         * @return unknown
597         * @deprecated
598         */
599        function moduleRequireOnce($module, $file) {
600               
601                return require_once(OWA_BASE_DIR.'/modules/'.$module.'/'.$file.'.php');
602        }
603       
604        /**
605         * module specific factory
606         *
607         * @param unknown_type $modulefile
608         * @param unknown_type $class_suffix
609         * @param unknown_type $params
610         * @return unknown
611         * @deprecated
612         */
613        function moduleFactory($modulefile, $class_suffix = null, $params = '') {
614               
615                list($module, $file) = split("\.", $modulefile);
616                $class = 'owa_'.$file.$class_suffix;
617               
618                // Require class file if class does not already exist
619                if(!class_exists($class)):     
620                        owa_lib::moduleRequireOnce($module, $file);
621                endif;
622                       
623                $obj = owa_lib::factory(OWA_BASE_DIR.'/modules/'.$module, '', $class, $params);
624                $obj->module = $module;
625               
626                return $obj;
627        }
628   
629        /**
630         * redirects borwser to a particular view
631         *
632         * @param unknown_type $data
633         */
634        function redirectToView($data) {
635                //print_r($data);
636                $c = &owa_coreAPI::configSingleton();
637                $config = $c->fetch('base');
638               
639                $control_params = array('view_method', 'auth_status');
640               
641               
642                $get = '';
643               
644                foreach ($data as $n => $v) {
645                       
646                        if (!in_array($n, $control_params)):                   
647                       
648                                $get .= $config['ns'].$n.'='.$v.'&';
649                       
650                        endif;
651                }
652                $new_url = sprintf($config['link_template'], $config['main_url'], $get);
653               
654                owa_lib::redirectBrowser($new_url);
655               
656                return;
657        }
658       
659        /**
660         * Displays a View without user authentication. Takes array of data as input
661         *
662         * @param array $data
663         * @deprecated
664         */
665        function displayView($data, $params = array()) {
666               
667                $view =  owa_lib::moduleFactory($data['view'], 'View', $params);
668               
669                return $view->assembleView($data);
670               
671        }
672       
673        function &coreAPISingleton() {
674               
675                static $api;
676               
677                if(!isset($api)):
678                        require_once('owa_coreAPI.php');
679                        $api = new owa_coreAPI;
680                endif;
681               
682                return $api;
683        }
684       
685        /**
686         * Create guid from string
687         *
688         * @param       string $string
689         * @return      integer
690         * @access      private
691         */
692        function setStringGuid($string) {
693                if (!empty($string)):
694                        return crc32(strtolower($string));
695                else:
696                        return;
697                endif;
698        }
699       
700        /**
701         * Add constraints into SQL where clause
702         *
703         * @param       array $constraints
704         * @return      string $where
705         * @access      public
706         */
707        function addConstraints($constraints) {
708