Beispiel #1
0
 /**
  * Метод получает экземпляр класса и, если нужно, кеширует его.
  */
 public static function getClassInstance($__DIR__, $subDir, $className, $parent, $caching = true)
 {
     if (!is_valid_file_name($className)) {
         return null;
         //---
     }
     $className = get_file_name($className);
     if ($className == $parent) {
         //Абстрактный класс/интерфейс лежит рядом с классами реализации - пропустим его
         return null;
     }
     //Абсолютный путь к классу
     $classPath = file_path(array($__DIR__, $subDir), $className, PsConst::EXT_PHP);
     //Ключ кеширования
     $cacheKey = md5($classPath);
     $CACHE = $caching ? SimpleDataCache::inst(__CLASS__, __FUNCTION__) : null;
     if ($CACHE && $CACHE->has($cacheKey)) {
         return $CACHE->get($cacheKey);
     }
     $INST = null;
     if (is_file($classPath)) {
         //Подключим данный класс
         require_once $classPath;
         //Проверим, существует ли класс
         $rc = PsUtil::newReflectionClass($className, false);
         $INST = $rc && $rc->isSubclassOf($parent) ? $rc->newInstance() : null;
     }
     if ($CACHE && $INST) {
         $CACHE->set($cacheKey, $INST);
     }
     return $INST;
 }
Beispiel #2
0
 /**
  * Метод вызывается для инициализации окружения:
  * 1. Директория ресурсов окружения будет подключена в Autoload
  * 2. Файл, включающий окружение, будет выполнен
  */
 public static function init()
 {
     if (self::$inited) {
         return;
         //---
     }
     self::$inited = true;
     //---
     /*
      * Проверим, нужно ли подключать окружение
      */
     if (self::isSkipInclude()) {
         return;
         //---
     }
     $env = self::env();
     if (!$env) {
         return;
         //---
     }
     $envDir = array_get_value($env, ConfigIni::environments());
     if (!$envDir) {
         return PsUtil::raise('Environment [{}] not found', $env);
     }
     if (!is_dir($envDir)) {
         return PsUtil::raise('Environment dir for [{}] not found', $env);
     }
     $envSrcDir = next_level_dir($envDir, DirManager::DIR_SRC);
     $envIncFile = file_path($envDir, $env, PsConst::EXT_PHP);
     if (!is_file($envIncFile)) {
         return PsUtil::raise('Environment include file for [{}] not found', $env);
     }
     $LOGGER = PsLogger::inst(__CLASS__);
     if ($LOGGER->isEnabled()) {
         $LOGGER->info('Including \'{}\' environment for context \'{}\'', $env, PsContext::describe());
         $LOGGER->info('Env dir:  {}', $envDir);
         $LOGGER->info('Src dir:  {}', $envSrcDir);
         $LOGGER->info('Inc file: {}', $envIncFile);
     }
     //Проинициализировано окружение
     self::$included = true;
     //Регистрируем директорию с классами, специфичными только для данного окружения
     Autoload::inst()->registerBaseDir($envSrcDir, false);
     //Выполним необходимое действие
     $PROFILER = PsProfiler::inst(__CLASS__);
     try {
         $LOGGER->info('{');
         $PROFILER->start($env);
         self::initImpl($LOGGER, $envIncFile);
         $secundomer = $PROFILER->stop();
         $LOGGER->info('}');
         $LOGGER->info('Inc file included for {} sec', $secundomer->getTime());
     } catch (Exception $ex) {
         $PROFILER->stop(false);
         $LOGGER->info('Inc file execution error: [{}]', $ex->getMessage());
         throw $ex;
         //---
     }
 }
Beispiel #3
0
/**
 * Base helper, accessible in controllers, views and models
 *
 * @filesource
 * @copyright  Copyright (c) 2008-2014, Kamil "Brego" Dzieliński
 * @license    http://opensource.org/licenses/mit-license.php The MIT License
 * @author     Kamil "Brego" Dzieliński <*****@*****.**>
 * @link       http://prank.brego.dk/ Prank's project page
 * @package    Prank
 * @subpackage Helpers
 * @since      Prank 0.25
 * @version    Prank 0.75
 */
function partial($name, $params = [])
{
    $registry = Registry::instance();
    $controller = $registry->current_controller;
    extract($params);
    extract($controller->view_variables);
    require file_path($registry->config->views, $controller->get_controller(), '_' . $name . '.php');
}
Beispiel #4
0
function configure()
{
    option('app_dir', file_path(dirname(option('root_dir')), 'app'));
    option('lib_dir', file_path(option('app_dir'), 'lib'));
    option('views_dir', file_path(option('app_dir'), 'views'));
    option('session', "app_session");
    option('debug', false);
    setlocale(LC_TIME, "ro_RO");
}
Beispiel #5
0
function dimpConsoleLog()
{
    global $CALLED_FILE;
    if ($CALLED_FILE) {
        $log = file_path(dirname($CALLED_FILE), get_file_name($CALLED_FILE), 'log');
        $FULL_LOG = PsLogger::controller()->getFullLog();
        $FULL_LOG = mb_convert_encoding($FULL_LOG, 'UTF-8', 'cp866');
        file_put_contents($log, $FULL_LOG);
    }
}
Beispiel #6
0
function test_file_path()
{
    $p = "/one/two/three";
    assert_equal(file_path('/one', 'two', 'three'), $p);
    assert_equal(file_path('/one', '/two', 'three'), $p);
    assert_equal(file_path('/one', 'two', '///three'), $p);
    assert_equal(file_path('/one', 'two', 'three/'), $p . '/');
    assert_equal(file_path('/one', 'two', 'three//'), $p . '/');
    assert_equal(file_path('/one', '\\two', '\\three//'), $p . '/');
}
 /**
  * Метод форматирует вывод Exception в html
  */
 public static function getHtml(Exception $exception)
 {
     //Вычитываем [exception.html] и производим замены
     try {
         return str_replace('{STACK}', ExceptionHelper::formatStackHtml($exception), file_get_contents(file_path(__DIR__, 'exception.html')));
     } catch (Exception $ex) {
         //Если в методе форматирования эксепшена ошибка - прекращаем выполнение.
         die("Exception [{$exception->getMessage()}] stack format error: [{$ex->getMessage()}]");
     }
 }
Beispiel #8
0
 function before_render($content_or_func, $layout, $locals, $view_path)
 {
     if (is_callable($content_or_func)) {
     } elseif (file_exists($view_path) && !array_key_exists('content', $locals)) {
         // a view file but not a layout
         $view_path = file_path(option('views_dir'), basename($content_or_func, ".html.php") . "_filtered.html.php");
     } else {
         # it's a string
         $content_or_func .= "∞FILTERED∞";
     }
     return array($content_or_func, $layout, $locals, $view_path);
 }
Beispiel #9
0
/**
 * a filter for rewriting views without short_open_tags
 *
 * @param string $view_path 
 * @return string $path to converted view file
 */
function render_filter_rewrite_short_tags($view_path)
{
    if (option('rewrite_short_tags') == true && (bool) @ini_get('short_open_tag') === false) {
        # cache path, maybe in tmp/cache/rsot_views/
        $cache_path = file_path(option('rewrite_sot_cache_dir'), $view_path);
        if (!file_exists($cache_path) || filemtime($cache_path) != filemtime($view_path)) {
            $view = file_get_contents($view_path);
            $transformed_view = preg_replace("/;*\\s*\\?>/", "; ?>", str_replace('<?=', '<?php echo ', $view));
            # TODO: store it in cache
            # …
        }
        $view_path = $cache_path;
    }
    return $view_path;
}
Beispiel #10
0
 /** @return DirItem */
 public static function inst($path, $name = null, $ext = null)
 {
     $absPath = normalize_path(file_path($path, $name, $ext));
     if (!$absPath || DIR_SEPARATOR == $absPath || PATH_BASE_DIR == $absPath || PATH_BASE_DIR == $absPath . DIR_SEPARATOR) {
         $absPath = PATH_BASE_DIR;
     } else {
         if (!starts_with($absPath, PATH_BASE_DIR)) {
             $absPath = next_level_dir(PATH_BASE_DIR, $absPath);
         }
     }
     if (array_key_exists($absPath, self::$items)) {
         return self::$items[$absPath];
     }
     $relPath = cut_string_start($absPath, PATH_BASE_DIR);
     $relPath = ensure_dir_startswith_dir_separator($relPath);
     return self::$items[$absPath] = new DirItem($relPath, $absPath);
 }
Beispiel #11
0
 /** @return DirItem */
 public static function inst($path, $name = null, $ext = null)
 {
     $itemPath = normalize_path(file_path($path, $name, $ext));
     $corePath = normalize_path(PATH_BASE_DIR);
     //Обезопасим пути, в которых есть русские буквы
     try {
         $itemPath = iconv('UTF-8', 'cp1251', $itemPath);
     } catch (Exception $e) {
         //Если произойдёт ошибка - игнорируем
     }
     $isAbs = starts_with($itemPath, $corePath);
     $absPath = $isAbs ? $itemPath : next_level_dir($corePath, $itemPath);
     if (array_key_exists($absPath, self::$items)) {
         return self::$items[$absPath];
     }
     $relPath = cut_string_start($absPath, $corePath);
     $relPath = ensure_starts_with($relPath, DIR_SEPARATOR);
     return self::$items[$absPath] = new DirItem($relPath, $absPath);
 }
 function index($id = null)
 {
     $data = $this->parent_account_model->getIdenticalColumn();
     debug($this->parent_account_model->db->last_query());
     if ($id == null) {
         $this->_set_flashdata('Invalid Feed reference key', 'error');
         redirect('home');
     }
     $id = trim($id);
     $activity_feed = $this->parent_account_model->getActivityFeedById($id);
     if (empty($activity_feed)) {
         $this->_set_flashdata('No activity feed found with the specified key', 'error');
         redirect('home');
     }
     $keywords = array();
     foreach (explode(' ', $activity_feed->description) as $keyword) {
         if (strlen($keyword) > 3) {
             $keywords[] = $keyword;
         }
     }
     $fb_app_id = $this->session->userdata('facebook_app_id');
     /*
      * OpenGraph Meta Settings
      */
     $this->data['title'] = $activity_feed->from . ' ' . $activity_feed->title;
     $this->data['description'] = $activity_feed->description;
     $this->data['keywords'] = implode(', ', $keywords);
     $this->data['author'] = 'Seedplane Development Team';
     $this->data['copyright'] = 'Seedplane';
     $this->data['app_name'] = 'seedplane';
     $this->data['social_type'] = 'article';
     $this->data['image'] = isset($activity_feed->image) && $activity_feed->image ? file_path('', $activity_feed->image, 'user_missing.png', 'uploads/default/') : '';
     $this->data['fb_app_id'] = isset($fb_app_id) && $fb_app_id ? $fb_app_id : '819064394807097';
     // end meta settings
     $this->data['activity_feed'] = $activity_feed;
     $this->ims_template->build('view_feed', $this->data);
 }
Beispiel #13
0
 public final function absFilePath($dirs, $fileName, $ext = null)
 {
     return file_path($this->absDirPath($dirs), $fileName, $ext);
 }
Beispiel #14
0
<?php

require_once '../ToolsResources.php';
$CALLED_FILE = __FILE__;
dolog(__FILE__ . ' called in ' . time());
file_append_contents(file_path(__DIR__, 'called.log'), time() . "\n");
                echo $activity_feed->activity_feed_id;
                ?>
"><?php 
                echo lang('share');
                ?>
</a></div>
                                <div class="innerWrapper">
                                    <input name="public_url" type="hidden" value="<?php 
                echo site_url('view_feed/index/' . $activity_feed->activity_feed_id);
                ?>
" />
                                    <?php 
                if ($activity_feed->image != '') {
                    ?>
                                        <div class="activity_image_div"><img src="<?php 
                    echo file_path("", $activity_feed->image, 'NoImageAvailable.jpg', 'uploads/default/');
                    ?>
"/></div>
                                    <?php 
                }
                ?>
                                    <div class="innerContent fli">
                                        <h3><?php 
                echo '<span class="activity_from">' . $activity_feed->from . '</span>' . '    ' . $activity_feed->title;
                ?>
</h3>
                                        <span class="timeLog"><?php 
                echo time_elapsed_string($activity_feed->date_time);
                ?>
</span>
                                        <?php 
Beispiel #16
0
/**
 * Returns an url composed of params joined with /
 * A param can be a string or an array.
 * If param is an array, its members will be added at the end of the return url
 * as GET parameters "&key=value".
 *
 * @param string or array $param1, $param2 ... 
 * @return string
 */
function url_for($params = null)
{
    $paths = array();
    $params = func_get_args();
    $GET_params = array();
    foreach ($params as $param) {
        if (is_array($param)) {
            $GET_params = array_merge($GET_params, $param);
            continue;
        }
        if (filter_var_url($param)) {
            $paths[] = $param;
            continue;
        }
        $p = explode('/', $param);
        foreach ($p as $v) {
            if ($v != "") {
                $paths[] = str_replace('%23', '#', rawurlencode($v));
            }
        }
    }
    $path = rtrim(implode('/', $paths), '/');
    if (!filter_var_url($path)) {
        # it's a relative URL or an URL without a schema
        $base_uri = option('base_uri');
        $path = file_path($base_uri, $path);
    }
    if (!empty($GET_params)) {
        $is_first_qs_param = true;
        $path_as_no_question_mark = strpos($path, '?') === false;
        foreach ($GET_params as $k => $v) {
            $qs_separator = $is_first_qs_param && $path_as_no_question_mark ? '?' : '&amp;';
            $path .= $qs_separator . rawurlencode($k) . '=' . rawurlencode($v);
            $is_first_qs_param = false;
        }
    }
    if (DIRECTORY_SEPARATOR != '/') {
        $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
    }
    return $path;
}
Beispiel #17
0
?>
"><?php 
echo lang('delete');
?>
</a></li>
                    
                   
                </ul>
            </div>      
            <div class="da-panel-content">
                <table class="da-table da-detail-view da-child-detail-head">
                    <tbody>
                        <tr class="dataTableHead">
                            <th>Logo</th>
                            <td class="logo_td"> <img src="<?php 
echo file_path('uploads/centre/', $data_all->logo, 'logo.gif');
?>
" height="26%;"></td>
                        </tr>
                    	<tr class="dataTableHead">
                        	<th>Centre Acronym</th>
                            <td><?php 
echo $data_all->name;
?>
</td>
                        </tr>
                        <tr class="dataTableHead">
                        	<th>Full Name</th>
                        	<td><?php 
echo $data_all->fullName;
?>
Beispiel #18
0
/**
 *  Generates thumbnails and extracts information from 2-D image files
 *
 */
function process_image($db, $fileid, $bigsize)
{
    global $USER, $system_settings;
    if (!$bigsize) {
        $bigsize = 300;
    }
    if (!$fileid) {
        return false;
    }
    $imagefile = file_path($db, $fileid);
    if (!file_exists($imagefile)) {
        return false;
    }
    $bigthumb = $system_settings['thumbnaildir'] . "/big/{$fileid}.jpg";
    $smallthumb = $system_settings['thumbnaildir'] . "/small/{$fileid}.jpg";
    $smallsize = $system_settings['smallthumbsize'];
    $convert = $system_settings['convert'];
    // make big thumbnail and get image info
    if (extension_loaded('gd') || extension_loaded('gd2')) {
        //Get Image size info
        list($width_orig, $height_orig, $image_type) = getimagesize($imagefile);
        switch ($image_type) {
            case 1:
                $im = imagecreatefromgif($imagefile);
                break;
            case 2:
                $im = imagecreatefromjpeg($imagefile);
                break;
            case 3:
                $im = imagecreatefrompng($imagefile);
                break;
            default:
                break;
        }
        /*** calculate the aspect ratio ***/
        $aspect_ratio = (double) $height_orig / $width_orig;
        /*** calulate the thumbnail width based on the height ***/
        $thumb_height = round($bigsize * $aspect_ratio);
        $newImg = imagecreatetruecolor($bigsize, $thumb_height);
        imagecopyresampled($newImg, $im, 0, 0, 0, 0, $bigsize, $thumb_height, $width_orig, $height_orig);
        imagejpeg($newImg, $bigthumb);
    } else {
        $command = "{$convert} -verbose -sample " . $bigsize . "x" . $bigsize . " {$action} \"{$imagefile}\" jpg:{$bigthumb}";
        exec($command, $result_str_arr, $status);
    }
    // make small thumbnail
    if (extension_loaded('gd') || extension_loaded('gd2')) {
        //Get Image size info
        list($width_orig, $height_orig, $image_type) = getimagesize($imagefile);
        switch ($image_type) {
            case 1:
                $im = imagecreatefromgif($imagefile);
                break;
            case 2:
                $im = imagecreatefromjpeg($imagefile);
                break;
            case 3:
                $im = imagecreatefrompng($imagefile);
                break;
            default:
                break;
        }
        /*** calculate the aspect ratio ***/
        $aspect_ratio = (double) $height_orig / $width_orig;
        /*** calulate the thumbnail width based on the height ***/
        $thumb_height = round($smallsize * $aspect_ratio);
        $newImg = imagecreatetruecolor($smallsize, $thumb_height);
        imagecopyresampled($newImg, $im, 0, 0, 0, 0, $smallsize, $thumb_height, $width_orig, $height_orig);
        imagejpeg($newImg, $smallthumb);
    } else {
        $command = "{$convert} -sample " . $smallsize . "x" . $smallsize . " {$action} \"{$imagefile}\" jpg:{$smallthumb}";
        `{$command}`;
    }
    // get size, mime, and type from image file.
    // Try exif function, if that fails use convert
    $sizearray = getimagesize($imagefile);
    $width = $sizearray[0];
    if ($width) {
        $height = $sizearray[1];
        $mime = $sizearray['mime'];
        switch ($sizearray[2]) {
            case 1:
                $filename_extension = 'GIF';
                break;
            case 2:
                $filename_extension = 'JPG';
                break;
            case 3:
                $filename_extension = 'PNG';
                break;
            case 4:
                $filename_extension = 'SWF';
                break;
            case 5:
                $filename_extension = 'PSD';
                break;
            case 6:
                $filename_extension = 'BMP';
                break;
            case 7:
                $filename_extension = 'TIFF';
                break;
            case 8:
                $filename_extension = 'TIFF';
                break;
            case 9:
                $filename_extension = 'JPC';
                break;
            case 10:
                $filename_extension = 'JP2';
                break;
            case 11:
                $filename_extension = 'JPX';
                break;
            case 12:
                $filename_extension = 'JB2';
                break;
            case 13:
                $filename_extension = 'SWC';
                break;
            case 14:
                $filename_extension = 'IFF';
                break;
        }
    } else {
        // get filetype and size in pixels from convert. Take first token after filesize.  Don't know if it always works.
        // appparently convert yields:
        // original filename, dimensions, Class, (optional) colordepht, size (in kb), filetype, ???, ???
        $convertresult[0] = strtok($result_str_arr[0], " ");
        $test = false;
        for ($i = 1; $i < 7; $i++) {
            $convertresult[$i] = strtok(" ");
            if ($i == 1) {
                $pixels = $convertresult[$i];
            }
            if ($test) {
                $filename_extension = $convertresult[$i];
                $test = false;
            }
            if (substr($convertresult[$i], -2) == 'kb') {
                $test = true;
            }
        }
        // extract pixel dimensions, this fails when there are spaces in the filename
        $width = (int) strtok($pixels, 'x+= >');
        $height = (int) strtok('x+= >');
    }
    if ($mime) {
        $db->Execute("UPDATE files SET mime='{$mime}' WHERE id={$fileid}");
    }
    $r = $db->Execute("SELECT id FROM images WHERE id={$fileid}");
    if (!$r->fields["id"]) {
        $query = "INSERT INTO images (id,x_size,y_size,xbt_size,ybt_size,xst_size,yst_size,type) VALUES ('{$fileid}', '{$width}', '{$height}', '{$bigsize}', '{$bigsize}', '{$smallsize}', '{$smallsize}', '{$filename_extension}')";
    } else {
        $query = "UPDATE images SET x_size='{$width}',y_size='{$height}',xbt_size='{$bigsize}',ybt_size='{$bigsize}',xst_size='{$smallsize}',yst_size='{$smallsize}',type='{$filename_extension}' WHERE id={$fileid}";
    }
    $db->Execute($query);
}
" ></div>
<div class="public_fb_buttons"><div class="fb-like" data-href="<?php 
echo current_url();
?>
" data-layout="button" data-action="like" data-show-faces="true" data-share="true"></div></div>
<div style="clear: both !important;"></div>
<div class="content_wraper">
    <div class="content_title"><h3><span> <?php 
echo isset($activity_feed->from) && $activity_feed->from ? $activity_feed->from : '';
?>
 </span><?php 
echo isset($activity_feed->title) && $activity_feed->title ? $activity_feed->title : '';
?>
</h3></div>
    <div class="content_wraper_img"><img src="<?php 
echo isset($activity_feed->image) && $activity_feed->image ? file_path('', $activity_feed->image, 'NoImageAvailable.jpg', 'uploads/default/') : '';
?>
"></div>

</div>
<div id="fb-root"></div>
<script>(function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id))
            return;
        js = d.createElement(s);
        js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.3";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
        </script>
        ?>
                        <li <?php 
        echo empty($teacher_name) ? 'height:100px' : '';
        ?>
">
                            <?php 
        $image = null;
        if (!empty($teacher_image)) {
            $hash = $teacher_image->avatar_hash;
            if (!empty($hash)) {
                $img = glob("uploads/avatar/*{$hash}.*", GLOB_BRACE);
                if (isset($img['0'])) {
                    $image = base_url($img['0']);
                }
            } else {
                $image = file_path("uploads/avatar/", $teacher_image->avatar, 'user_missing.png', 'uploads/default/');
            }
        } else {
            $image = base_url('uploads/default/user_missing.png');
        }
        ?>
 <br />
                            <div class="teacher_image">

                                <img src="<?php 
        echo $image;
        ?>
" alt="teacher_image">
                            </div>
                            <div class="teacher_comment">
                                <?php 
Beispiel #21
0
function executeProcess(array $argv)
{
    $CLASS_PATTERN = file_get_contents(file_path(__DIR__, 'class.txt'));
    $METHOD_PATTERN = file_get_contents(file_path(__DIR__, 'method.txt'));
    /*
     * Название тестового файла.
     * Для проверки мы сначала удалим класс для него, если он был, потом проверим, что за класс был сгенерирован.
     */
    $TEST_MESSAGES_FILE = 'ExampleSdkProcessMessages';
    //Убедимся, что тестовый .msgs существует и удалим тестовый .php файл
    $TEST_PHP_DI = DirItem::inst(__DIR__ . '/classes', $TEST_MESSAGES_FILE, PsConst::EXT_PHP)->remove();
    $TEST_MSGS_DI = DirItem::inst(__DIR__ . '/classes', $TEST_MESSAGES_FILE, PsConst::EXT_MSGS);
    check_condition($TEST_MSGS_DI->isFile(), "File {$TEST_MSGS_DI->getAbsPath()} must exists");
    dolog('Loading all files, ended with Messages.msgs');
    //TODO - после нужно получать эту информацию из какого-нибудь места
    $exceptDirs[] = DirManager::autogen()->relDirPath();
    $exceptDirs[] = DirManager::resources()->relDirPath();
    $exceptDirs[] = DirManager::stuff()->relDirPath();
    //$exceptDirs = array();
    $items = DirManager::inst()->getDirContentFull(null, function (DirItem $di) {
        dolog($di->getAbsPath());
        return $di->isFile() && ends_with($di->getName(), 'Messages.msgs');
    }, $exceptDirs);
    dolog('Message files for processing: {}', count($items));
    //Проверим, что был выбран тестовый файл
    check_condition(in_array($TEST_MSGS_DI, $items, true), "Test file [{$TEST_MESSAGES_FILE}] is not included");
    //Удалим его из массива...
    array_remove_value($items, $TEST_MSGS_DI, true);
    //И поместим наверх, чтобы он был обработан первым
    array_unshift($items, $TEST_MSGS_DI);
    /* @var $msgsDi DirItem */
    foreach ($items as $msgsDi) {
        dolog('PROCESSING [{}]', $msgsDi->getAbsPath());
        //Сбросим методы
        $METHODS = array();
        //Извлечём название класса
        $CLASS = $msgsDi->getNameNoExt();
        //DirItem файла с сообщениями php
        $classDi = DirItem::inst($msgsDi->getDirname(), $CLASS, PsConst::EXT_PHP);
        //Получаем сообщения из файла .msgs
        $messages = $msgsDi->getFileAsProps();
        foreach ($messages as $MSG_KEY => $MGG_VALUE) {
            dolog(' >> {}={}', $MSG_KEY, $MGG_VALUE);
            //Получим список всех параметров из макросов ({0}, {1}, {2} и т.д.)
            preg_match_all("/\\{(.+?)\\}/", $MGG_VALUE, $args);
            $args = array_values(array_unique($args[1]));
            sort($args, SORT_NUMERIC);
            $ARGS = array();
            for ($index = 0; $index < count($args); $index++) {
                $arg = $args[$index];
                $lineDescr = PsStrings::replaceWithBraced('[{}] in line [{}={}]', $msgsDi->getRelPath(), $MSG_KEY, $MGG_VALUE);
                check_condition(is_inumeric($arg), "Invalid argument [{$arg}] for {$lineDescr}");
                check_condition($index == $args[$index], "Missing index [{$index}] for {$lineDescr}");
                $ARGS[] = '$p' . $index;
            }
            $ARGS = join(', ', $ARGS);
            //Добавляем метод
            dolog(" A: {}::{} ({})", $CLASS, $MSG_KEY, $ARGS);
            $PARAMS['SUPPORT_CLASS'] = PsMsgs::getClass();
            $PARAMS['MESSAGE'] = $MGG_VALUE;
            $PARAMS['FUNCTION'] = $MSG_KEY;
            $PARAMS['ARGS'] = $ARGS;
            $METHODS[] = PsStrings::replaceMapBracedKeys($METHOD_PATTERN, $PARAMS);
        }
        dolog('Made methods: ({})', count($METHODS));
        if ($METHODS) {
            $PARAMS['FILE'] = $msgsDi->getAbsPath();
            $PARAMS['CLASS'] = $CLASS;
            $PARAMS['DATE'] = date(DF_PS);
            $PARAMS['METHODS'] = "\n" . join("\n\n", $METHODS) . "\n";
            $CLASS_PHP = PsStrings::replaceMapBracedKeys($CLASS_PATTERN, $PARAMS);
            $classDi->putToFile($CLASS_PHP);
        }
        /*
         * Если обрабатываем тестовый файл - проверим его
         */
        //TEST CLASS VALIDATION START >>>
        if ($msgsDi->equals($TEST_MSGS_DI)) {
            dolog('');
            dolog('Validating test class {}', $TEST_MESSAGES_FILE);
            //Проверим, что .php был сгенерирован
            check_condition($TEST_PHP_DI->isFile(), "File {$TEST_PHP_DI->getAbsPath()} was not created!");
            //Проверим, что для каждого сообщения был создан метод
            $methods = PsUtil::newReflectionClass($TEST_MESSAGES_FILE)->getMethods();
            $messages = $TEST_MSGS_DI->getFileAsProps();
            check_condition(count($methods) == count($messages), 'Methods count missmatch, check ' . $TEST_PHP_DI->getAbsPath());
            /* @var $method ReflectionMethod */
            foreach ($methods as $method) {
                check_condition(array_key_exists($method->getName(), $messages), "No method {$TEST_MESSAGES_FILE}::" . $method->getName());
            }
            //Проверим, что возвращают методы тестового сгенерированного класса
            function doTest($className, $methodName, array $params, $expected)
            {
                $method = "{$className}::{$methodName}";
                $actual = call_user_func_array($method, $params);
                dolog("{}({})='{}', Expected='{}'", $method, join(', ', $params), $actual, $expected);
                check_condition($actual == $expected, "{$actual} != {$expected}");
            }
            doTest($TEST_MESSAGES_FILE, 'message1', array(), 'Message 1');
            doTest($TEST_MESSAGES_FILE, 'message2', array('a', 'b', 'c'), 'Parametred a,c,b');
            dolog('Test class is valid!');
        }
        //TEST CLASS VALIDATION END <<<
    }
    //# DirItems validation end
}
Beispiel #22
0
fwrite($fp, "\n");
$r = $db->Execute("SELECT {$fields} FROM " . $tableinfo->realname);
while ($r->fields['id'] && !$r->EOF) {
    $rowvalues = getvalues($db, $tableinfo, $fields, 'id', $r->fields['id']);
    foreach ($rowvalues as $row) {
        if (is_array($row)) {
            // files will be exported to the directory files
            if ($row['datatype'] == 'file') {
                $files = get_files($db, $tableinfo->name, $row['recordid'], $row['columnid'], 0);
                fwrite($fp, $pre_seperator);
                for ($i = 0; $i < sizeof($files); $i++) {
                    $filecounter++;
                    // write a temp table with all the file info,and provide an comma separated list of ids to that table here
                    fwrite($ff, ++$filenr . "\t" . $files[$i]['name'] . "\t" . $files[$i]['mime'] . "\t" . $files[$i]['size'] . "\t" . $files[$i]['type'] . "\n");
                    fwrite($fp, $filenr . ',');
                    $path = file_path($db, $files[$i]['id']);
                    // $cpstr="cp $path {$filedir}{$filenr}_{$files[$i]['name']}";
                    //`$cpstr`;
                    copy($path, "{$filedir}{$filenr}_{$files[$i]['name']}");
                }
                fwrite($fp, $post_seperator);
            } else {
                if ($valuesOnly) {
                    fwrite($fp, $pre_seperator . $row['values'] . $post_seperator);
                } else {
                    if ($row['datatype'] == 'textlong') {
                        // strip every kind of new line tag first
                        $row['values'] = strtr($row['values'], "\t\n\r\\m", '    ');
                        fwrite($fp, $pre_seperator . $row['values'] . $post_seperator);
                    } else {
                        // strip every kind of new line tag first
Beispiel #23
0
/**
 * Returns a string to output
 * 
 * It might use a a template file or function, a formatted string (like {@link sprintf()}).
 * It could be embraced by a layout or not.
 * Local vars can be passed in addition to variables made available with the {@link set()}
 * function.
 *
 * @param string $content_or_func 
 * @param string $layout 
 * @param string $locals 
 * @return string
 */
function render($content_or_func, $layout = '', $locals = array())
{
    $args = func_get_args();
    $content_or_func = array_shift($args);
    $layout = count($args) > 0 ? array_shift($args) : layout();
    $view_path = file_path(option('views_dir'), $content_or_func);
    $vars = array_merge(set(), $locals);
    $infinite_loop = false;
    # Avoid infinite loop: this function is in the backtrace ?
    if (function_exists($content_or_func)) {
        $back_trace = debug_backtrace();
        while ($trace = array_shift($back_trace)) {
            if ($trace['function'] == strtolower($content_or_func)) {
                $infinite_loop = true;
                break;
            }
        }
    }
    if (function_exists($content_or_func) && !$infinite_loop) {
        ob_start();
        call_user_func($content_or_func, $vars);
        $content = ob_get_clean();
    } elseif (file_exists($view_path)) {
        ob_start();
        extract($vars);
        include $view_path;
        $content = ob_get_clean();
    } else {
        $content = vsprintf($content_or_func, $vars);
    }
    if (empty($layout)) {
        return $content;
    }
    return render($layout, null, array('content' => $content));
}
Beispiel #24
0
/**
 * Определим функцию, которая выполнит все действия - не будем лишними переменными засорять глобальное пространство
 */
function psExecuteAjaxAction()
{
    /*
     * Название действия должно быть в переменной запроса. Оно же - название класса, который будет выполнен.
     * Группа действия должны быть не обязательна, при определении действия группа нужна обязательно.
     */
    $actionName = RequestArrayAdapter::inst()->str(AJAX_ACTION_PARAM);
    $actionGroup = RequestArrayAdapter::inst()->str(AJAX_ACTION_GROUP_PARAM, 'client');
    if (!PsCheck::notEmptyString($actionName) || !PsCheck::notEmptyString($actionGroup)) {
        return json_error('Не передан код действия или его группа');
        //---
    }
    /*
     * Экземпляр класса действия - должен быть наследником AbstractAjaxAction
     */
    $action = null;
    /*
     * Поищем в проектных действиях, они для нас имеют больший приоритет
     */
    foreach (ConfigIni::ajaxActionsAbs($actionGroup) as $dirAbsPath) {
        $classPath = file_path($dirAbsPath, $actionName, PsConst::EXT_PHP);
        if (is_file($classPath)) {
            /*
             * Нашли файл. Загрузим и проверим, является ли он наследником AbstractAjaxAction
             */
            require_once $classPath;
            if (!PsUtil::isInstanceOf($actionName, AbstractAjaxAction::getClassName())) {
                continue;
                //---
            }
            $action = new $actionName();
            break;
            //---
        }
    }
    /*
     * Проверим, существует ли действие.
     * Для безопасности не будем писать детали обработки.
     */
    if (!$action || !$action instanceof AbstractAjaxAction) {
        return json_error('Действие не опеределено');
        //---
    }
    /*
     * Выполняем
     */
    $result = null;
    try {
        $result = $action->execute();
    } catch (Exception $e) {
        $result = $e->getMessage();
    }
    /*
     * Проверим результат
     */
    if ($result instanceof AjaxSuccess) {
        json_success($result->getJsParams());
    } else {
        json_error($result ? $result : 'Ошибка выполнения действия');
    }
}
        $k = 0;
        foreach ($assessment->album_items as $image) {
            ?>
                            <?php 
            if ($image->item_type == 'photo') {
                ?>
                            <li style="margin:10%!important;">
                                <a class="group" rel="group" title="<?php 
                echo $image->description;
                ?>
" href="<?php 
                echo file_path('uploads/album_item/', $image->item, 'NoImageAvailable.jpg', 'uploads/default/');
                ?>
">
                                    <img src="<?php 
                echo file_path('uploads/album_item/', $image->item, 'NoImageAvailable.jpg', 'uploads/default/');
                ?>
">
                                </a>
                            </li>
                            <?php 
            } else {
                ?>
                            <li style="margin:10%!important;">
                                <a class="group"  rel="group" title="<?php 
                echo $image->description;
                ?>
" href="<?php 
                echo site_url('gallery/download_video/' . $image->item);
                ?>
">
Beispiel #26
0
}
$items = $dm->getDirContent($SRC_DIR, DirItemFilter::IMAGES);
if (isEmpty($items)) {
    return;
    //---
}
//Массив для сохранения информации о картинках
$images = array();
//Создадим $OUT_DIR
$dm->makePath($OUT_DIR);
$outputDir = $dm->absDirPath($OUT_DIR);
foreach ($items as $item) {
    $name = $item->getNameNoExt();
    $srcImg = SimpleImage::inst()->load($item);
    $w = $srcImg->getWidth();
    $h = $srcImg->getHeight();
    $outImg = SimpleImage::inst()->create($w, $h, null);
    for ($x = 0; $x < $w; $x++) {
        for ($y = 0; $y < $h; $y++) {
            $rgb = $srcImg->colorAt($x, $y);
            if ($rgb != 16777215 && $rgb != 255) {
                $outImg->copyFromAnother($srcImg, $x, $y, $x, $y, 1, 1);
            }
        }
    }
    $filename = file_path($outputDir, $name, 'png');
    $outImg->save($filename, IMAGETYPE_PNG)->close();
    $srcImg->close();
    $images[] = array('rel' => file_path($OUT_DIR, $name, 'png'), 'rels' => file_path($SRC_DIR, $item->getName()), 'name' => $name);
}
saveResult2Html('pngs.tpl', array('items' => $images), __DIR__);
Beispiel #27
0
/**
 * Returns an url composed of params joined with /
 * A param can be a string or an array.
 * If param is an array, its members will be added at the end of the return url
 * as GET parameters "&key=value".
 *
 * @param string or array $param1, $param2 ... 
 * @return string
 */
function url_for($params = null)
{
    $paths = array();
    $params = func_get_args();
    $GET_params = array();
    foreach ($params as $param) {
        if (is_array($param)) {
            $GET_params = array_merge($GET_params, $param);
            continue;
        }
        if (filter_var_url($param)) {
            $paths[] = $param;
            continue;
        }
        $p = explode('/', $param);
        foreach ($p as $v) {
            if (!empty($v)) {
                $paths[] = str_replace('%23', '#', rawurlencode($v));
            }
        }
    }
    $path = rtrim(implode('/', $paths), '/');
    if (!empty($GET_params)) {
        foreach ($GET_params as $k => $v) {
            $path .= '&amp;' . rawurlencode($k) . '=' . rawurlencode($v);
        }
    }
    if (!filter_var_url($path)) {
        # it's a relative URL or an URL without a schema
        $base_uri = option('base_uri');
        $path = file_path($base_uri, $path);
    }
    if (DIRECTORY_SEPARATOR != '/') {
        $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
    }
    return $path;
}
Beispiel #28
0
 /**
  * Метод возвращает элемент в директории указанной сущности
  * 
  * @param string $foldedUnique - код фолдинга [lib-p]
  * @param string $entity - код сущности
  * @param mixed $dirs - поддиректории
  * @param string $name - название файла
  * @param string $ext - расширение файла
  */
 public static function getEntityChild($foldedUnique, $entity, $dirs, $name = null, $ext = null)
 {
     return file_path(array(self::getEntity($foldedUnique, $entity), $dirs), $name, $ext);
 }
Beispiel #29
0
/**
 * Returns an url composed of params joined with /
 *
 * @param string $params,...
 * @return string
 */
function url_for($params = null)
{
    $paths = array();
    $params = func_get_args();
    $first = true;
    foreach ($params as $param) {
        if ($first) {
            if (filter_var($param, FILTER_VALIDATE_URL)) {
                $paths[] = $param;
                continue;
            }
        }
        $p = explode('/', $param);
        foreach ($p as $v) {
            if (!empty($v)) {
                $paths[] = str_replace('%23', '#', rawurlencode($v));
            }
        }
    }
    $path = rtrim(implode('/', $paths), '/');
    if (!filter_var($path, FILTER_VALIDATE_URL)) {
        # it's a relative URL or an URL without a schema
        $base_uri = option('base_uri');
        $path = file_path($base_uri, $path);
    }
    if (DIRECTORY_SEPARATOR != '/') {
        $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
    }
    return $path;
}
echo site_url('account/centre_profile/edit');
?>
" class="backable_link da-button gray" ><?php 
echo lang('update');
?>
</a>
                </span>
            </span>
        </div>
        <div class="da-panel-content">
            <table class="da-table da-detail-view da-child-detail-head">
                <tbody>
                    <tr>
                        <th>Logo</th>
                        <td class="logo_td"><img src="<?php 
echo file_path('uploads/centre/', $centre->logo, 'logo.gif');
?>
" width="128px"></td>
                    </tr>
                    <tr>
                        <th>Centre Acronym</th>
                        <td><?php 
echo $centre->name;
?>
</td>
                    </tr>
                    <tr>
                    	<th>Full Name</th>
                    	<td><?php 
echo $centre->fullName;
?>