ICanBoogie/ICanBoogie 3.0.x
  • Namespace
  • Class

Namespaces

  • ICanBoogie
    • Autoconfig
    • Binding
    • Core
    • Routing
    • Session

Classes

  • AlreadyAuthenticated
  • Core
  • Debug
  • Helpers
  • Hooks
  • Logger
  • LogLevel
  • SessionWithEvent

Interfaces

  • LoggerInterface

Traits

  • AppAccessor
  • LoggerTrait

Exceptions

  • CoreAlreadyBooted
  • CoreAlreadyInstantiated
  • CoreAlreadyRunning
  • CoreNotInstantiated

Constants

  • TOKEN_ALPHA
  • TOKEN_ALPHA_UPCASE
  • TOKEN_NUMERIC
  • TOKEN_SYMBOL
  • TOKEN_SYMBOL_WIDE

Functions

  • app
  • boot
  • excerpt
  • generate_token
  • generate_token_wide
  • get_autoconfig
  • log
  • log_error
  • log_info
  • log_success
  • log_time
  • resolve_app_paths
  • resolve_instance_name
  • strip_root
  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 440 441 442 443 444 445 446 447 
<?php

/*
 * This file is part of the ICanBoogie package.
 *
 * (c) Olivier Laviale <olivier.laviale@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ICanBoogie;

/*
 * Core
 */

/**
 * Resolves application instance name.
 *
 * @return string
 */
function resolve_instance_name()
{
    $instance = getenv('ICANBOOGIE_INSTANCE');

    if (!$instance && PHP_SAPI == 'cli')
    {
        $instance = 'cli';
    }

    if (!$instance && !empty($_SERVER['SERVER_NAME']))
    {
        $instance = $_SERVER['SERVER_NAME'];
    }

    return $instance;
}

/**
 * Resolves the paths where the application can look for config, locale, modules, and more.
 *
 * Consider an application root directory with the following directories:
 *
 * <pre>
 * all
 * cli
 * default
 * dev
 * icanboogie.org
 * org
 * </pre>
 *
 * The directory "all" contains resources that are shared between all the sites. It is always
 * added if present. The directory "default" is only added if there no directory matches
 * `$instance`.
 *
 * To resolve the matching directory, `$instance` is first broken into parts and the most
 * specific ones are removed until a corresponding directory is found. For instance, given
 * the instance name "www.icanboogie.localhost", the following directories are tried:
 * "www.icanboogie.localhost", "icanboogie.localhost", and finally "localhost".
 *
 * @param string $root The absolute path of a root directory.
 * @param string|null $instance An instance name. If `$instance` is `null`, the instance name
 * defaults as follows:
 *
 * - The `ICANBOOGIE_INSTANCE` environment variable is defined, it is used as instance name.
 * - The application runs from the CLI, "cli" is used.
 * - `$_SERVER['SERVER_NAME']` is defined, it is used as instance name.
 *
 * @return string[] An array of absolute paths, ordered from the less specific to
 * the most specific.
 */
function resolve_app_paths($root, $instance = null)
{
    static $cache = [];

    if ($instance === null)
    {
        $instance = resolve_instance_name();
    }

    $cache_key = $root . '#' . $instance;

    if (isset($cache[$cache_key]))
    {
        return $cache[$cache_key];
    }

    $root = rtrim($root, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
    $parts = explode('.', $instance);
    $paths = [];

    while ($parts)
    {
        $try = $root . implode('.', $parts);

        if (!file_exists($try))
        {
            array_shift($parts);


            continue;
        }

        $paths[] = $try . DIRECTORY_SEPARATOR;

        break;
    }

    if (!$paths && file_exists($root . 'default'))
    {
        $paths[] = $root . 'default' . DIRECTORY_SEPARATOR;
    }

    if (file_exists($root . 'all'))
    {
        array_unshift($paths, $root . 'all' . DIRECTORY_SEPARATOR);
    }

    $cache[$cache_key] = $paths;

    return $paths;
}

/**
 * Returns the autoconfig.
 *
 * The path of the autoconfig is defined by the {@link AUTOCONFIG_PATHNAME} constant.
 *
 * The `app-root` and `app-paths` values are updated. `app-root` is resolved from `root`, which may
 * gives `false` if the application root is not defined. The value `app-paths` is returned by
 * the {@link resolve_app_paths()} function with `app-root` as parameter.
 *
 * The filters defined in `filters` are invoked to alter the autoconfig.
 *
 * @return array
 */
function get_autoconfig()
{
    static $autoconfig;

    if ($autoconfig === null)
    {
        if (!file_exists(AUTOCONFIG_PATHNAME))
        {
            trigger_error("The autoconfig file has not been generated. Check the `script` section of your composer.json file. https://github.com/ICanBoogie/ICanBoogie#generating-the-autoconfig-file", E_USER_ERROR);
        }

        $autoconfig = (require AUTOCONFIG_PATHNAME) + [

            'app-root' => 'protected'

        ];

        $root = $autoconfig['root'];
        $autoconfig['app-root'] = realpath($root . DIRECTORY_SEPARATOR . $autoconfig['app-root']);
        $autoconfig['app-paths'] = array_merge($autoconfig['app-paths'], resolve_app_paths($autoconfig['app-root']));

        foreach ($autoconfig['filters'] as $filter)
        {
            call_user_func_array($filter, [ &$autoconfig ]);
        }
    }

    return $autoconfig;
}

/**
 * Instantiates a {@link Core} instance with the autoconfig and boots it.
 *
 * @return Core
 */
function boot()
{
    $app = new Core( get_autoconfig() );
    $app->boot();

    return $app;
}

/**
 * Returns the {@link Core} instance.
 *
 * @return Core
 *
 * @throws CoreNotInstantiated if the core has not been instantiated yet.
 */
function app()
{
    $app = Core::get();

    if (!$app)
    {
        throw new CoreNotInstantiated;
    }

    return $app;
}

/*
 * Logger
 */

/**
 * Logs a debug message.
 *
 * @param string $message Message pattern.
 * @param array $params The parameters used to format the message.
 * @param string $level
 */
function log($message, array $params=[], $level=LogLevel::DEBUG)
{
    static $logger;

    if (!$logger)
    {
        $logger = app()->logger;
    }

    $logger->{ $level }($message, $params);
}

/**
 * Logs a success message.
 *
 * @param string $message Message pattern.
 * @param array $params The parameters used to format the message.
 */
function log_success($message, array $params=[])
{
    log($message, $params, LogLevel::SUCCESS);
}

/**
 * Logs an error message.
 *
 * @param string $message Message pattern.
 * @param array $params The parameters used to format the message.
 */
function log_error($message, array $params=[])
{
    log($message, $params, LogLevel::ERROR);
}

/**
 * Logs an info message.
 *
 * @param string $message Message pattern.
 * @param array $params The parameters used to format the message.
 */
function log_info($message, array $params=[])
{
    log($message, $params, LogLevel::INFO);
}

/**
 * Logs a debug message associated with a timing information.
 *
 * @param string $message Message pattern.
 * @param array $params The parameters used to format the message.
 */
function log_time($message, array $params=[])
{
    static $last;

    $now = microtime(true);

    $add = '<var>[';

    $add .= '∑' . number_format($now - $_SERVER['REQUEST_TIME_FLOAT'], 3, '\'', '') . '"';

    if ($last)
    {
        $add .= ', +' . number_format($now - $last, 3, '\'', '') . '"';
    }

    $add .= ']</var>';

    $last = $now;

    $message = $add . ' ' . $message;

    log($message, $params);
}

/*
 * Utils
 */

const TOKEN_NUMERIC = "23456789";
const TOKEN_ALPHA = "abcdefghjkmnpqrstuvwxyz";
const TOKEN_ALPHA_UPCASE = "ABCDEFGHJKLMNPQRTUVWXYZ";
const TOKEN_SYMBOL = "!$=@#";
const TOKEN_SYMBOL_WIDE = '%&()*+,-./:;<>?@[]^_`{|}~';

define('ICanBoogie\TOKEN_NARROW', TOKEN_NUMERIC . TOKEN_ALPHA . TOKEN_SYMBOL);
define('ICanBoogie\TOKEN_MEDIUM', TOKEN_NUMERIC . TOKEN_ALPHA . TOKEN_SYMBOL . TOKEN_ALPHA_UPCASE);
define('ICanBoogie\TOKEN_WIDE', TOKEN_NUMERIC . TOKEN_ALPHA . TOKEN_SYMBOL . TOKEN_ALPHA_UPCASE . TOKEN_SYMBOL_WIDE);

/**
 * Generate a password.
 *
 * @param int $length The length of the password. Default: 8
 * @param string $possible The characters that can be used to create the password.
 * If you defined your own, pay attention to ambiguous characters such as 0, O, 1, l, I...
 * Default: {@link TOKEN_NARROW}
 *
 * @return string
 */
function generate_token($length=8, $possible=TOKEN_NARROW)
{
    return Helpers::generate_token($length, $possible);
}

/**
 * Generate a 512 bit (64 chars) length token from {@link TOKEN_WIDE}.
 *
 * @return string
 */
function generate_token_wide()
{
    return Helpers::generate_token(64, TOKEN_WIDE);
}

/**
 * Creates an excerpt of an HTML string.
 *
 * The following tags are preserved: A, P, CODE, DEL, EM, INS and STRONG.
 *
 * @param string $str HTML string.
 * @param int $limit The maximum number of words.
 *
 * @return string
 */
function excerpt($str, $limit=55)
{
    static $allowed_tags = [

        'a', 'p', 'code', 'del', 'em', 'ins', 'strong'

    ];

    $str = strip_tags(trim($str), '<' . implode('><', $allowed_tags) . '>');
    $str = preg_replace('#(<p>|<p\s+[^\>]+>)\s*</p>#', '', $str);

    $parts = preg_split('#<([^\s>]+)([^>]*)>#m', $str, 0, PREG_SPLIT_DELIM_CAPTURE);

    # i+0: text
    # i+1: markup ('/' prefix for closing markups)
    # i+2: markup attributes

    $rc = '';
    $opened = [];

    foreach ($parts as $i => $part)
    {
        if ($i % 3 == 0)
        {
            $words = preg_split('#(\s+)#', $part, 0, PREG_SPLIT_DELIM_CAPTURE);

            foreach ($words as $w => $word)
            {
                if ($w % 2 == 0)
                {
                    if (!$word) // TODO-20100908: strip punctuation
                    {
                        continue;
                    }

                    $rc .= $word;

                    if (!--$limit)
                    {
                        break;
                    }
                }
                else
                {
                    $rc .= $word;
                }
            }

            if (!$limit)
            {
                break;
            }
        }
        else if ($i % 3 == 1)
        {
            if ($part[0] == '/')
            {
                $rc .= '<' . $part . '>';

                array_shift($opened);
            }
            else
            {
                array_unshift($opened, $part);

                $rc .= '<' . $part . $parts[$i + 1] . '>';
            }
        }
    }

    if (!$limit)
    {
        $rc .= ' <span class="excerpt-warp">[…]</span>';
    }

    if ($opened)
    {
        $rc .= '</' . implode('></', $opened) . '>';
    }

    return $rc;
}

/**
 * Removes the `DOCUMENT_ROOT` from the provided path.
 *
 * Note: Because this function is usually used to create URL path from server path, the directory
 * separator '\' is replaced by '/'.
 *
 * @param string $pathname
 *
 * @return string
 */
function strip_root($pathname)
{
    $root = rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR);
    $root = strtr($root, DIRECTORY_SEPARATOR == '/' ? '\\' : '/', DIRECTORY_SEPARATOR);
    $pathname = strtr($pathname, DIRECTORY_SEPARATOR == '/' ? '\\' : '/', DIRECTORY_SEPARATOR);

    if ($root && strpos($pathname, $root) === 0)
    {
        $pathname = substr($pathname, strlen($root));
    }

    if (DIRECTORY_SEPARATOR != '/')
    {
        $pathname = strtr($pathname, DIRECTORY_SEPARATOR, '/');
    }

    return $pathname;
}
ICanBoogie/ICanBoogie 3.0.x API documentation generated by ApiGen