srchub

srchub Git Source Tree


Root/pluf/src/Pluf.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# ***** END LICENSE BLOCK ***** */
 
/**
 * The main class of the framework. From where all start.
 *
 * The __autoload function is automatically set.
 */
class Pluf
{
    /**
     * Start the Plume Framework.
     *
     * Load the configuration files.
     *
     * @param string Configuration file to use
     */
    static function start($config)
    {
        $GLOBALS['_PX_starttime'] = microtime(true);
        $GLOBALS['_PX_uniqid'] = uniqid($GLOBALS['_PX_starttime'], true);
        $GLOBALS['_PX_signal'] = array();
        $GLOBALS['_PX_locale'] = array();
        Pluf::loadConfig($config);
        date_default_timezone_set(Pluf::f('time_zone', 'Europe/Berlin'));
        mb_internal_encoding(Pluf::f('encoding', 'UTF-8'));
        mb_regex_encoding(Pluf::f('encoding', 'UTF-8'));
    }
 
    /**
     * Load the given configuration file.
     *
     * The configuration is saved in the $GLOBALS['_PX_config'] array.
     * The relations between the models are loaded in $GLOBALS['_PX_models'].
     *
     * @param string Configuration file to load.
     */
    static function loadConfig($config_file)
    {
        if (false !== ($file=Pluf::fileExists($config_file))) {
            $GLOBALS['_PX_config'] = require $file;
        } else {
            throw new Exception('Configuration file does not exist: '.$config_file);
        }
        // Load the relations for each installed application. Each
        // application folder must be in the include path.
        self::loadRelations(!Pluf::f('debug', false));
    }
 
    /**
     * Get the model relations and signals.
     *
     * If not in debug mode, it will automatically cache the
     * information. This allows one include file when many
     * applications and thus many includes are needed.
     *
     * Signals and relations are cached in the same file as the way to
     * go for signals is to put them in the relations.php file.
     *
     * @param bool Use the cache (true)
     */
    static function loadRelations($usecache=true)
    {
        $GLOBALS['_PX_models'] = array();
        $GLOBALS['_PX_models_init_cache'] = array();
        $apps = Pluf::f('installed_apps', array());
        $cache = Pluf::f('tmp_folder').'/Pluf_relations_cache_'.md5(serialize($apps)).'.phps';
        if ($usecache and file_exists($cache)) {
            list($GLOBALS['_PX_models'],
                 $GLOBALS['_PX_models_related'],
                 $GLOBALS['_PX_signal']) = include $cache;
            return;
        }
        $m = $GLOBALS['_PX_models'];
        foreach ($apps as $app) {
            $m = array_merge_recursive($m, require $app.'/relations.php');
        }
        $GLOBALS['_PX_models'] = $m;
 
        $_r = array(
                    'relate_to' => array(),
                    'relate_to_many' => array(),
                    );
        foreach ($GLOBALS['_PX_models'] as $model => $relations) {
            foreach ($relations as $type => $related) {
                foreach ($related as $related_model) {
                    if (!isset($_r[$type][$related_model])) {
                        $_r[$type][$related_model] = array();
                    }
                    $_r[$type][$related_model][] = $model;
                }
            }
        }
        $_r['foreignkey'] = $_r['relate_to'];
        $_r['manytomany'] = $_r['relate_to_many'];
        $GLOBALS['_PX_models_related'] = $_r;
 
        // $GLOBALS['_PX_signal'] is automatically set by the require
        // statement and possibly in the configuration file.
        if ($usecache) {
            $s = var_export(array($GLOBALS['_PX_models'],
                                  $GLOBALS['_PX_models_related'],
                                  $GLOBALS['_PX_signal']), true);
            if (@file_put_contents($cache, '<?php return '.$s.';'."\n",
                                   LOCK_EX)) {
                chmod($cache, 0755);
            }
        }
    }
 
    /**
     * Access a configuration variable.
     *
     * @param string Configuration variable
     * @param mixed Possible default value if value is not set ('')
     * @return mixed Configuration variable or default value if not defined.
     */
    static function f($cfg, $default='')
    {
        if (isset($GLOBALS['_PX_config'][$cfg])) {
            return $GLOBALS['_PX_config'][$cfg];
        }
        return $default;
    }
 
    /**
     * Access an array of configuration variables having a given
     * prefix.
     *
     * @param string Prefix.
     * @param bool Strip the prefix from the keys (false).
     * @return array Configuration variables.
     */
    static function pf($pfx, $strip=false)
    {
        $ret = array();
        $pfx_len = strlen($pfx);
        foreach ($GLOBALS['_PX_config'] as $key=>$val) {
            if (0 === strpos($key, $pfx)) {
                if (!$strip) {
                    $ret[$key] = $val;
                } else {
                    $ret[substr($key, $pfx_len)] = $val;
                }
            }
        }
        return $ret;
    }
 
 
    /**
     * Returns a given object.
     *
     * Loads automatically the corresponding class file if needed.
     * If impossible to get the class $model, exception is thrown.
     *
     * @param string Model to load.
     * @param mixed Extra parameters for the constructor of the model.
     */
    public static function factory($model, $params=null)
    {
        if ($params !== null) {
            return new $model($params);
        }
        return new $model();
    }
 
    /**
     * Load a class depending on its name.
     *
     * Throw an exception if not possible to load the class.
     *
     * @param string Class to load.
     */
    public static function loadClass($class)
    {
        if (class_exists($class, false)) {
            return;
        }
        $file = str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php';
        include $file;
        if (!class_exists($class, false)) {
            $error = 'Impossible to load the class: '.$class."\n".
                'Tried to include: '.$file."\n".
                'Include path: '.get_include_path();
            throw new Exception($error);
        }
    }
 
    /**
     * Load a function depending on its name.
     *
     * The implementation file of the function
     * MyApp_Youpla_Boum_Stuff() is MyApp/Youpla/Boum.php That way it
     * is possible to group all the related function in one file.
     *
     * Throw an exception if not possible to load the function.
     *
     * @param string Function to load.
     */
    public static function loadFunction($function)
    {
        if (function_exists($function)) {
            return;
        }
        $elts = explode('_', $function);
        array_pop($elts);
        $file = implode(DIRECTORY_SEPARATOR, $elts) . '.php';
        if (false !== ($file=Pluf::fileExists($file))) {
            include $file;
        }
        if (!function_exists($function)) {
            throw new Exception('Impossible to load the function: '.$function);
        }
    }
 
 
    /**
     * Hack for [[php file_exists()]] that checks the include_path.
     *
     * Use this to see if a file exists anywhere in the include_path.
     *
     * <code type="php">
     * $file = 'path/to/file.php';
     * if (Pluf::fileExists('path/to/file.php')) {
     *     include $file;
     * }
     * </code>
     *
     * @credits Paul M. Jones <pmjones@solarphp.net>
     
     * @param string $file Check for this file in the include_path.
     * @return mixed Full path to the file if the file exists and
     *         is readable in the include_path, false if not.
     */
    public static function fileExists($file)
    {
        $file = trim($file);
        if (!$file) {
            return false;
        }
        // using an absolute path for the file?
        // dual check for Unix '/' and Windows '\',
        // or Windows drive letter and a ':'.
        $abs = ($file[0] == '/' || $file[0] == '\\' || $file[1] == ':');
        if ($abs && file_exists($file)) {
            return $file;
        }
        // using a relative path on the file
        $path = explode(PATH_SEPARATOR, ini_get('include_path'));
        foreach ($path as $dir) {
            // strip Unix '/' and Windows '\'
            $target = rtrim($dir, '\\/').DIRECTORY_SEPARATOR.$file;
            if (file_exists($target)) {
                return $target;
            }
        }
        // never found it
        return false;
    }
 
    /**
     * Helper to load the default database connection.
     *
     * This method is just dispatching to the function define in the
     * configuration by the 'db_get_connection' key or use the default
     * 'Pluf_DB_getConnection'. If you want to use your own function,
     * take a look at the Pluf_DB_getConnection function to use the
     * same approach for your method.
     *
     * The extra parameters can be used to selectively connect to a
     * given database. When the ORM is getting a connection, it is
     * passing the current model as parameter. That way you could get
     * different databases for different models.
     *
     * @param mixed Extra parameters.
     * @return resource DB connection.
     */
    public static function &db($extra=null)
    {
        $func = Pluf::f('db_get_connection', 'Pluf_DB_getConnection');
        Pluf::loadFunction($func);
        $a = $func($extra);
        return $a;
    }
}
 
 
/**
 * Translate a string.
 *
 * @param string String to be translated.
 * @return string Translated string.
 */
function __($str)
{
    $locale = (isset($GLOBALS['_PX_current_locale'])) ? $GLOBALS['_PX_current_locale'] : 'en';
    if (!empty($GLOBALS['_PX_locale'][$locale][$str][0])) {
        return $GLOBALS['_PX_locale'][$locale][$str][0];
    }
    return $str;
}
 
/**
 * Translate the plural form of a string.
 *
 * @param string Singular form of the string.
 * @param string Plural form of the string.
 * @param int Number of elements.
 * @return string Translated string.
 */
function _n($sing, $plur, $n)
{
    $locale = (isset($GLOBALS['_PX_current_locale'])) ? $GLOBALS['_PX_current_locale'] : 'en';
    if (isset($GLOBALS['_PX_current_locale_plural_form'])) {
        $pform = $GLOBALS['_PX_current_locale_plural_form'];
    } else {
        $pform = Pluf_Translation::getPluralForm($locale);
    }
    $index = Pluf_Translation::$pform($n);
    if (!empty($GLOBALS['_PX_locale'][$locale][$sing.'#'.$plur][$index])) {
        return $GLOBALS['_PX_locale'][$locale][$sing.'#'.$plur][$index];
    }
    // We have no translations or default English
    if ($n == 1) {
        return $sing;
    }
    return $plur;
}
 
/**
 * Autoload function.
 *
 * @param string Class name.
 */
function __autoload($class_name)
{
    try {
        Pluf::loadClass($class_name);
    } catch (Exception $e) {
        if (Pluf::f('debug')) {
            print $e->getMessage();
            die();
        }
        eval("class $class_name {
          function __construct() {
            throw new Exception('Class $class_name not found');
          }
           
          static function __callstatic(\$m, \$args) {
            throw new Exception('Class $class_name not found');
          }
        }");
    }
}
 
/**
 * Exception to catch the PHP errors.
 *
 * @credits errd
 */
class PlufErrorHandlerException extends Exception
{
    public function setLine($line)
    {
        $this->line = $line;
    }
 
    public function setFile($file)
    {
        $this->file = $file;
    }
}
 
/**
 * The function that is the real error handler.
 */
function PlufErrorHandler($code, $string, $file, $line)
{
    if (0 == error_reporting()) return false;
    if (E_STRICT == $code
        &&
        (
         0 === strpos($file, Pluf::f('pear_path','/usr/share/php/'))
         or
         false !== strripos($file, 'pear') // if pear in the path, ignore
         )
        ) {
        return;
    }
    $exception = new PlufErrorHandlerException($string, $code);
    $exception->setLine($line);
    $exception->setFile($file);
    throw $exception;
}
 
// Set the error handler only if not performing the unittests.
if (!defined('IN_UNIT_TESTS')) {
    set_error_handler('PlufErrorHandler', error_reporting());
}
 
 
/**
 * Shortcut needed all over the place.
 *
 * Note that in some cases, we need to escape strings not in UTF-8, so
 * this is not possible to safely use a call to htmlspecialchars. This
 * is why str_replace is used.
 *
 * @param string Raw string
 * @return string HTML escaped string
 */
function Pluf_esc($string)
{
    return str_replace(array('&',     '"',      '<',    '>'),
                       array('&', '"', '<', '>'),
                       (string) $string);
}

Archive Download this file

Branches

Number of commits:
Page rendered in 0.10747s using 11 queries.