예제 #1
0
function smarty_block_nobr($params, $content, Smarty_Internal_Template &$smarty)
{
    if (isEmpty($content)) {
        return;
    }
    echo '<span class="nowrap">' . $content . '</span>';
}
예제 #2
0
 public static final function finalize(PsLoggerInterface $LOGGER, $CONTENT)
 {
     //Проверим на пустоту
     if (isEmpty($CONTENT)) {
         return $CONTENT;
     }
     $call = ++self::$call;
     //Создадим экземпляр финализатора и вызовем его
     $class = get_called_class();
     $PROFILER = PsProfiler::inst($class);
     $inst = new $class($LOGGER, $PROFILER);
     $PROFILER->start(__FUNCTION__);
     $SECUNDOMER = Secundomer::startedInst();
     $LOGGER->infoBox(">>> CALLED {$call}. {$class}");
     try {
         $CONTENT = $inst->doFinalize($CONTENT);
         $PROFILER->stop();
         $SECUNDOMER->stop();
     } catch (Exception $ex) {
         $PROFILER->stop(false);
         $LOGGER->infoBox("Exception occured while calling {$class}::finalize. Message: " . $ex->getMessage());
         throw $ex;
     }
     $LOGGER->infoBox("<<< CALL {$call}. {$class} FINISHED IN " . $SECUNDOMER->getAverage() . ' seconds');
     return $CONTENT;
 }
예제 #3
0
파일: block.h5.php 프로젝트: ilivanoff/www
function smarty_block_h5($params, $content, Smarty_Internal_Template &$smarty)
{
    if (isEmpty($content)) {
        return;
    }
    echo "<h5 class=\"colored\">{$content}</h5>";
}
 /**
  * Efetua uma busca complexa a partir dos parâmetros passados
  * @param array $Paranmetros
  * @param int $CurrentPage
  * @param int $PorPagina
  * @param string $OrderBy
  * @return Pagination
  */
 function Busca(array $Paranmetros = null, $CurrentPage = 1, $PorPagina = 10, $OrderBy = 'rand()')
 {
     $Termos = 'WHERE a.status != 99';
     $Places = [];
     if ($Paranmetros) {
         foreach ($Paranmetros as $key => $value) {
             if (!isEmpty($value) and !empty($key)) {
                 switch ($key) {
                     case 'data':
                         $Termos .= " AND ((a.inicio = a.fim  AND a.inicio = '0000-00-00') OR (:data BETWEEN a.inicio AND a.fim))";
                         $Places['data'] = Date::data($value);
                         break;
                     case 'dia':
                         $Termos .= ' AND (a.dias LIKE "%[*]%" OR a.dias LIKE CONCAT("%[",:dia,"]%"))';
                         $Places['dia'] = $value;
                         break;
                     case 'status':
                     case 'ref':
                         $Termos .= " AND a.{$key} = :{$key}";
                         $Places[$key] = $value;
                         break;
                     case 'title':
                         $Termos .= ' AND (a.title CONCAT("%",:title,"%"))';
                         $Places['title'] = $value;
                         break;
                 }
             }
         }
     }
     return $this->ListaPagination("{$Termos} ORDER BY {$OrderBy}", $Places, $CurrentPage, $PorPagina);
 }
예제 #5
0
function smarty_block_strike($params, $content, Smarty_Internal_Template &$smarty)
{
    if (isEmpty($content)) {
        return;
    }
    echo "<span class=\"strike\">{$content}</span>";
}
예제 #6
0
function validateSession()
{
    //$result = isset($_SESSION['user:id']) && strlen($_SESSION['user:id']) > 0
    //       && isset($_SESSION['user:loggedin']) && $_SESSION['user:loggedin'] > (date('YmdHi') - 30);
    $result = !isEmpty($_SESSION, 'user:id') && !isEmpty($_SESSION, 'user:loggedin') && $_SESSION['user:loggedin'] > date('YmdHi') - 30;
    return $result;
}
예제 #7
0
 protected function getResource($info)
 {
     $ret = array();
     $resources = DB::table("hot_resources")->skip((int) $info['base'])->take((int) $info['count'])->get();
     if (!$resources || isEmpty($resources)) {
         return $ret;
     }
     foreach ($resources as $resource) {
         if (Cache::has($resource->name)) {
             $ret[] = Cache::get($resource->name);
         } else {
             $info = array();
             $info['name'] = $resource->name;
             $info['type'] = $resource->type;
             $info['bt_url_720p'] = $resource->bt_url_720p;
             $info['bt_url_1080p'] = $resource->bt_url_1080p;
             $info['bt_url_720p_tc'] = $resource->bt_url_720p_tc;
             $info['bt_url_1080p_tc'] = $resource->bt_url_1080p_tc;
             $info['bt_url_other'] = $resource->bt_url_other;
             $info['netdisk_url'] = $resource->netdisk_url;
             $info['http_url'] = $resource->http_url;
             $info['cover'] = $resource->cover;
             //$this->getResourceinfo($info); TBD
             $ret[] = $info;
         }
     }
     return $ret;
 }
예제 #8
0
function smarty_block_nl2br($params, $content, Smarty_Internal_Template &$smarty)
{
    if (isEmpty($content)) {
        return;
    }
    echo nl2br(trim($content));
}
예제 #9
0
 /**
  * Метод безопасно получает контент.
  * В случае возникновения ошибки возвращает её стек.
  */
 public static function getContent($objOrTpl, $method = 'buildContent')
 {
     $isCallable = is_callable($objOrTpl);
     $isTpl = $objOrTpl instanceof Smarty_Internal_Template;
     if (!$isCallable && !$isTpl) {
         check_condition(is_object($objOrTpl), 'Not object passed to ' . __FUNCTION__);
         PsUtil::assertMethodExists($objOrTpl, $method);
     }
     $returned = null;
     $flushed = null;
     ob_start();
     ob_implicit_flush(false);
     try {
         if ($isCallable) {
             $returned = call_user_func($objOrTpl);
         } else {
             if ($isTpl) {
                 $returned = $objOrTpl->fetch();
             } else {
                 $returned = $objOrTpl->{$method}();
             }
         }
     } catch (Exception $ex) {
         ob_end_clean();
         return ExceptionHandler::getHtml($ex);
     }
     $flushed = ob_get_contents();
     ob_end_clean();
     return isEmpty($returned) ? isEmpty($flushed) ? null : $flushed : $returned;
 }
예제 #10
0
/**
 * Function to handle HTTP-POST-requests.
 * @param Array, $requestData are the requested data
 */
function post(array $requestData)
{
    $logger = Logger::getLogger(basename(__FILE__));
    if (!isEmpty($requestData, 'username') && !isEmpty($requestData, 'password')) {
        sessionDestroy();
        if (__checkPassword('ADMINS', $requestData)) {
            $_SESSION['user:isAdmin'] = true;
        } elseif (__checkPassword('PASSWORDS', $requestData)) {
            $_SESSION['user:isAdmin'] = false;
        } else {
            header(HTTP_VERSION . ' ' . HTTP_401);
            return;
        }
        $_SESSION['user:id'] = $requestData['username'];
        $_SESSION['user:loggedin'] = date('YmdHi');
        session_write_close();
        $responseData = array('session_name' => session_name(), 'session_id' => session_id(), 'username' => $requestData['username']);
        if ($_SESSION['user:isAdmin']) {
            $responseData['isAdmin'] = true;
        }
        $logger->info("Login was successful for  " . $_SESSION['user:id'] . ". Current session: " . session_id());
        header(HTTP_VERSION . ' ' . HTTP_200);
        return $responseData;
    }
    header(HTTP_VERSION . ' ' . HTTP_401);
}
예제 #11
0
function smarty_block_tooldescr($params, $content, Smarty_Internal_Template &$template)
{
    if (isEmpty($content)) {
        return;
    }
    $content = trim($content);
    $content = nl2br($content);
    echo "<div class=\"tool_descr\">{$content}</div>";
}
function isFieldsEmpty($loginDetails, $errorMsg)
{
    if (isEmpty($loginDetails)) {
        userExists($loginDetails, $errorMsg);
    } else {
        $errorMsg = "Username and/or password fields cannot be left blank";
        errorMessage($errorMsg);
    }
}
예제 #13
0
 public static function validateOldPass($oldPass)
 {
     if (isEmpty($oldPass)) {
         return 'required';
     }
     if (!PsUser::inst()->checkPassword($oldPass)) {
         return 'remote';
     }
     return false;
 }
예제 #14
0
파일: min.php 프로젝트: mpetrovich/dash
function min($collection)
{
    if (isEmpty($collection)) {
        return null;
    }
    $min = reduce($collection, function ($min, $value) {
        return \min($min, $value);
    }, +INF);
    return $min;
}
예제 #15
0
파일: max.php 프로젝트: mpetrovich/dash
function max($collection)
{
    if (isEmpty($collection)) {
        return null;
    }
    $max = reduce($collection, function ($max, $value) {
        return \max($max, $value);
    }, -INF);
    return $max;
}
 /**
  * Store a newly created resource in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function store(Request $request)
 {
     $input = $request->all();
     if (!isEmpty($input['filepath'])) {
         $imgPath = $this->imageUpload($input['filepath']);
         $input['filepath'] = $imgPath;
     } else {
         $input['filepath'] = "modules/image.jpeg";
     }
     Modules::create($input);
     return redirect('BARD_modules')->with('status', 'Create successfully');
 }
예제 #17
0
파일: any.php 프로젝트: mpetrovich/dash
function any($collection, $predicate)
{
    if (isEmpty($collection)) {
        return false;
    }
    foreach ($collection as $key => $value) {
        if (call_user_func($predicate, $value, $key)) {
            return true;
        }
    }
    return false;
}
예제 #18
0
 public function test()
 {
     $key = getenv('CUSTOMER_KEY');
     if (strlen($key) === 0) {
         $this->markTestSkipped("must set CUSTOMER_KEY env");
     }
     $oauth = new OAuth($key, "http://example.com/");
     $requestToken = $oauth->fetchRequestToken();
     assertThat($requestToken, logicalNot(isEmpty()));
     $authorizeUrl = $oauth->generateAuthorizeUrl($requestToken);
     assertThat($authorizeUrl, logicalNot(isEmpty()));
 }
예제 #19
0
 /**
  * Метод декодирования шаблонных сообщений
  * 
  * @return TemplateMessageContent
  */
 public function decodeTemplateMsg(DiscussionMsg $msg)
 {
     try {
         check_condition($msg->isTemplated(), "Сообщение {$msg} не шаблонизировано");
         $result = $this->getFoldedEntityByDbCode($msg->getTemplateId())->getClassInst()->decodeMsg($msg);
         if ($result instanceof TemplateMessageContent) {
             return $result;
         }
         raise_error(is_string($result) && !isEmpty($result) ? $result : 'Шаблонное сообщение обработано некорректно');
     } catch (Exception $ex) {
         return new TemplateMessageError($ex);
     }
 }
예제 #20
0
 public function testEmpty()
 {
     isEmpty(0);
     isEmpty('');
     isEmpty(null);
     isEmpty('0');
     isEmpty(0.0);
     isEmpty(array());
     isNotEmpty(array(0));
     isNotEmpty(true);
     isNotEmpty('1');
     isNotEmpty(1);
 }
function checkIsbn($isbn)
{
    global $lang;
    if (isEmpty($isbn)) {
        return $lang['please_specify_ISBN'];
    }
    if (!isIsbn($isbn)) {
        return $isbn . ' ' . $lang['not_EAN_not_ISBN'];
    }
    if (isIsbn($isbn) and detectIsbnError($isbn)) {
        return $isbn . ' ' . $lang['ISBN_with_error'];
    }
    return NULL;
}
예제 #22
0
function htmlHead($title, $lang, $charset)
{
    $realTitle = !isEmpty($title) ? $title : "Default title";
    $realLang = !isEmpty($lang) ? $lang : "en";
    $realCharset = !isEmpty($charset) ? $charset : "UTF-8";
    echo '
        <!DOCTYPE html>
        <html>
            <head lang="' . $realLang . '">
                <meta charset="' . $realCharset . '">
                <title>' . $realTitle . '</title>
                <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
            </head>
            <body>
        ';
}
예제 #23
0
파일: block.ol.php 프로젝트: ilivanoff/www
function smarty_block_ol($params, $content, Smarty_Internal_Template &$smarty)
{
    if (isEmpty($content)) {
        return;
        //---
    }
    $params['class'] = to_array(array_get_value('class', $params));
    $params['class'][] = 'block_ol';
    $strings = explode("\n", trim($content));
    $lis = array();
    foreach ($strings as $string) {
        if (!isEmpty($string)) {
            $lis[] = '<li>' . trim($string) . '</li>';
        }
    }
    $content = join('', $lis);
    return PsHtml::html2('ol', $params, $content);
}
 /**
  * Busca complexa
  * @param array $Parans
  * @param int $Pagina
  * @param int $PorPagina
  * @return Pagination
  */
 function busca(array $Parans = null, $Pagina = 1, $PorPagina = 10)
 {
     $Termos = 'WHERE a.status != 99';
     $Places = [];
     if ($Parans) {
         foreach ($Parans as $key => $value) {
             if (!isEmpty($value) and !empty($key)) {
                 switch ($key) {
                     case 'uf':
                         $Termos .= " AND (estado.{$key} = :{$key} OR estado.id = :{$key})";
                         $Places[$key] = $value;
                         break;
                 }
             }
         }
     }
     return $this->ListaPagination("{$Termos} ORDER BY estado.title ASC, a.title ASC", $Places, $Pagina, $PorPagina);
 }
예제 #25
0
function smarty_block_exercise($params, $content, Smarty_Internal_Template &$template)
{
    if (isEmpty($content)) {
        return;
    }
    $id = value_Array('id', $params);
    /* @var $ex GymEx */
    $ex = GymManager::getInstance()->getExercise($id);
    $content = trim($content);
    $name = value_Array('name', $params);
    $name = $name ? $name : ($ex ? $ex->getName() : '');
    $class = $ex ? GymManager::getInstance()->getClass($ex) : '';
    $exTemplate = $template->smarty->createTemplate('gym/exercise.tpl');
    $exTemplate->assign('c_id', IdHelper::gymExId($id));
    $exTemplate->assign('c_name', $name);
    $exTemplate->assign('c_class', $class);
    $exTemplate->assign('c_body', $content);
    $exTemplate->display();
}
예제 #26
0
function smarty_block_sortable($params, $content, Smarty_Internal_Template &$smarty)
{
    if (!$content) {
        return;
        //---
    }
    $params = ArrayAdapter::inst($params);
    $sep = $params->str('sep');
    $strings = explode("\n", trim($content));
    $res = array();
    foreach ($strings as $str) {
        if (isEmpty($str)) {
            continue;
        }
        $items = explode('||', $str);
        $res[] = array('l' => trim($items[0]), 'r' => trim($items[1]), 's' => $sep);
    }
    PSSmarty::template('common/sortable.tpl', array('strings' => $res))->display();
}
예제 #27
0
 private function addReplaces($PAGE_CONTENT)
 {
     //Прежде, чем вызвать нормализацию страницы, нужно вырезать все textareas
     $pattern = "/<textarea[^>]*>(.*?)<\\/textarea>/si";
     $matches = array();
     preg_match_all($pattern, $PAGE_CONTENT, $matches);
     if (!empty($matches)) {
         $textareas = $matches[0];
         //<textarea name="tpl">content</textarea>
         $contents = $matches[1];
         //content
         for ($i = 0; $i < count($contents); $i++) {
             $content = $contents[$i];
             $textarea = $textareas[$i];
             if (isEmpty($content)) {
                 continue;
             }
             $this->addReplace($textarea);
         }
     }
 }
예제 #28
0
 /**
  * Основной метод, выполняющий выполнение Ajax действия.
  * 
  * @return AjaxSuccess
  */
 public final function execute()
 {
     $id = get_called_class();
     check_condition(!$this->processed, "Действие [{$id}] уже выполнено.");
     $this->processed = true;
     //Не будем портить глобальный массив $_REQUEST, создав копию адаптера
     $params = RequestArrayAdapter::inst()->copy();
     check_condition($params->str(AJAX_ACTION_PARAM) == $id, "Действие [{$id}] не может быть выполнено.");
     $params->remove(AJAX_ACTION_PARAM);
     $params->remove(AJAX_ACTION_GROUP_PARAM);
     //Проверка доступа
     AuthManager::checkAccess($this->getAuthType());
     //Если пользователь зарегистрирован, как администратор - подключим ресурсы админа
     //ps_admin_on();
     //Проверка обязательных параметров
     foreach (to_array($this->getRequiredParamKeys()) as $key) {
         if (!$params->has($key)) {
             return "Не передан обязательный параметр [{$key}].";
         }
     }
     //Проверка активности
     if ($this->isCheckActivity() && !ActivityWatcher::isCanMakeAction()) {
         return 'Таймаут не закончился.';
     }
     //Вызываем обработку данных
     PsProfiler::inst('AjaxProfiler')->start($id);
     $result = $this->executeImpl($params);
     PsProfiler::inst('AjaxProfiler')->stop();
     if (isEmpty($result)) {
         return "Действие [{$id}] выполнено некорректно - возвращён пустой результат.";
     }
     if (is_object($result) && $result instanceof AjaxSuccess) {
         //SUCCESS
         //Зарегистрируем активноcть пользователя (только в случае успеха, так как пользователь мог просто ошибиться в воде данных)
         if ($this->isCheckActivity()) {
             ActivityWatcher::registerActivity();
         }
     }
     return $result;
 }
예제 #29
0
function smarty_block_post_href($params, $content, Smarty_Internal_Template &$smarty)
{
    if (isEmpty($content)) {
        return;
    }
    /*
     * text - текст ссылки
     * Также может быть вставлен произвольный текст
     */
    $text = trim($content);
    $text = $text == '.' ? null : $text;
    /* @var $post Post */
    $post = value_Array('post', $params);
    $post = $post instanceof PostContentProvider ? $post->getPost() : $post;
    $sub = value_Array('sub', $params);
    $blank = !isEmptyInArray('blank', $params);
    $handler = null;
    if ($post) {
        $handler = Handlers::getInstance()->getPostsProcessorByPostType($post->getPostType());
    } else {
        $id = value_Array(array('id', 'post_id'), $params);
        $ident = value_Array(array('ident', 'post_ident'), $params);
        check_condition($id || $ident, 'Не переданы уникальный код или идентификатор поста.');
        $handler = Handlers::getInstance()->getPostsProcessorByPostType($params['type']);
        $post = $id ? $handler->getPost($id, true) : $handler->getPostByIdent($ident, true);
    }
    /*
     * Выкидываем служебные ключи, а остальное - возвращаем
     */
    unset($params['sub']);
    unset($params['blank']);
    unset($params['post']);
    unset($params['type']);
    unset($params['id']);
    unset($params['post_id']);
    unset($params['ident']);
    unset($params['post_ident']);
    echo $handler->postHref($post, $text, $sub, $params, $blank);
}
예제 #30
0
function smarty_block_page_href($params, $content, Smarty_Internal_Template &$smarty)
{
    if (isEmpty($content)) {
        return;
    }
    $code = value_Array('code', $params);
    $code = $code ? $code : BASE_PAGE_INDEX;
    $sub = value_Array('sub', $params);
    $title = value_Array('title', $params);
    $classes = value_Array('class', $params);
    $blank = !isEmptyInArray('blank', $params);
    $http = !isEmptyInArray('http', $params);
    $urlParams = array();
    foreach ($params as $key => $val) {
        if (starts_with($key, 'p_')) {
            $urlParams[substr($key, 2)] = $val;
        }
    }
    $content = trim($content);
    $content = $content == '.' ? null : $content;
    return WebPage::inst($code)->getHref($content, $blank, $classes, $http, $urlParams, $sub, $title);
}