Example #1
2
function _submit($stationTag = null)
{
    if ($stationTag === null) {
        trace("brata missing stationId", __FILE__, __LINE__, __METHOD__);
        rest_sendBadRequestResponse(400, "missing stationId");
        // doesn't return
    }
    $station = Station::getFromTag($stationTag);
    if ($station === false) {
        trace("brata can't find station stationTag=" . $stationTag, __FILE__, __LINE__, __METHOD__);
        rest_sendBadRequestResponse(404, "can't find station stationTag=" . $stationTag);
        // doesn't return
    }
    $json = json_getObjectFromRequest("POST");
    // won't return if an error happens
    json_checkMembers("message,team_id", $json);
    $team = Team::getFromPin($json['team_id']);
    if ($team === false) {
        trace("can't find team from team " . $json['team_id']);
        rest_sendBadRequestResponse(404, "can't find team pin=" . $json['team_id']);
    }
    $stationType = new StationType($station->get('typeId'), -1);
    if ($stationType === false) {
        trace("can't find station type stationTag = " . $stationTag, __FILE__, __LINE__, __METHOD__);
        rest_sendBadRequestResponse(500, "can't find station type stationTag=" . $stationTag);
    }
    try {
        $xxxData = XXXData::factory($stationType->get('typeCode'));
        $msg = $xxxData->brataSubmit($json['message'], $team, $station, $stationType);
        json_sendObject(array('message' => $msg));
    } catch (InternalError $ie) {
        rest_sendBadRequestResponse($ie->getCode(), $ie->getMessage());
    }
}
Example #2
0
function query_cache($options)
{
    global $QUERY_CACHE_CACHE;
    if (strpos('u.birthday < 1970', $options['query']) === true) {
        die('ERROR!!!');
    }
    $options['category'] = isset($options['category']) ? $options['category'] : 'other';
    $options['max_delay'] = isset($options['max_delay']) ? $options['max_delay'] : 300;
    $path = PATHS_INCLUDE . 'cache/query_cache/' . $options['category'] . '/';
    $filename = md5($options['query']) . '.phpserialized';
    if (isset($QUERY_CACHE_CACHE[$filename])) {
        return $QUERY_CACHE_CACHE[$filename];
    }
    if (!is_dir($path)) {
        mkdir($path);
    }
    if (!file_exists($path . $filename)) {
        trace('new_query_cache_' . $options['category'], $options['query']);
    }
    if (filemtime($path . $filename) < time() - $options['max_delay']) {
        $result = mysql_query($options['query']) or report_sql_error($query, __FILE__, __LINE__);
        while ($row = mysql_fetch_assoc($result)) {
            $data[] = $row;
        }
        $serialized = serialize($data);
        //trace('query_cache', 'Creating file for query: ' . $options['query']);
        file_put_contents($path . $filename, $serialized);
    } else {
        $data = unserialize(file_get_contents($path . $filename));
    }
    $QUERY_CACHE_CACHE[$filename] = $data;
    return $data;
}
 public function run(&$_data)
 {
     $engine = strtolower(C('TMPL_ENGINE_TYPE'));
     if ('think' == $engine) {
         //[sae] 采用Think模板引擎
         if ($this->checkCache($_data['file'])) {
             // 缓存有效
             SaeMC::include_file(md5($_data['file']) . C('TMPL_CACHFILE_SUFFIX'), $_data['var']);
         } else {
             $tpl = Think::instance('ThinkTemplate');
             // 编译并加载模板文件
             $tpl->fetch($_data['file'], $_data['var']);
         }
     } else {
         // 调用第三方模板引擎解析和输出
         $class = 'Template' . ucwords($engine);
         if (is_file(CORE_PATH . 'Driver/Template/' . $class . '.class.php')) {
             // 内置驱动
             $path = CORE_PATH;
         } else {
             // 扩展驱动
             $path = EXTEND_PATH;
         }
         if (require_cache($path . 'Driver/Template/' . $class . '.class.php')) {
             $tpl = new $class();
             $tpl->fetch($_data['file'], $_data['var']);
         } else {
             // 类没有定义
             throw_exception(L('_NOT_SUPPERT_') . ': ' . $class);
         }
     }
     //[sae] 添加trace信息。
     trace(array('[SAE]核心缓存' => $_SERVER['HTTP_APPVERSION'] . '/' . RUNTIME_FILE, '[SAE]模板缓存' => $_SERVER['HTTP_APPVERSION'] . '/' . md5($_data['file']) . C('TMPL_CACHFILE_SUFFIX')));
 }
Example #4
0
 /**
  * Return array of all plugins based on plugin files on filesystem
  *
  * @param none
  * @return array
  */
 static function getAllPlugins()
 {
     trace(__FILE__, 'getAllPlugins()');
     $results = array();
     $dir = APPLICATION_PATH . '/plugins';
     $dirs = get_dirs($dir, false);
     foreach ((array) $dirs as $plugin) {
         if (file_exists($dir . '/' . $plugin . '/init.php') && is_file($dir . '/' . $plugin . '/init.php')) {
             $results[$plugin] = '-';
         }
     }
     // now sort by name
     ksort($results);
     // now get activated plugins
     $conditions = array('`installed` = 1');
     $plugins = Plugins::findAll(array('conditions' => $conditions));
     trace(__FILE__, 'getAllPlugins() - all plugins retrieved from database');
     foreach ((array) $plugins as $plugin) {
         trace(__FILE__, 'getAllPlugins() - foreach: ' . $plugin->getName());
         if (array_key_exists($plugin->getName(), $results)) {
             $results[$plugin->getName()] = $plugin->getPluginId();
         } else {
             // TODO : remove from DB here??
         }
     }
     return $results;
 }
Example #5
0
 public static function send($msg, $detail, $level = self::NOTIC, $mobile = null)
 {
     //判断是否定义需要发送短信
     if (!in_array($level, explode(',', C('SMS_ALERT_LEVEL')))) {
         return;
     }
     //判断发送频率
     $mc = memcache_init();
     $is_send = $mc->get('think_sms_send');
     //如果已经发送,则不发送
     if ($is_send === 'true') {
         $status = 'not send';
     } else {
         $sms = apibus::init('sms');
         if (is_null($mobile)) {
             $mobile = C('SMS_ALERT_MOBILE');
         }
         $mc = memcache_init();
         $obj = $sms->send($mobile, mb_substr(C('SMS_ALERT_SIGN') . $msg, 0, 65, 'utf-8'), "UTF-8");
         if ($sms->isError($obj)) {
             $status = 'failed';
         } else {
             $status = 'success';
             $mc->set('think_sms_send', 'true', 0, C('SMS_ALERT_INTERVAL'));
         }
     }
     //记录日志
     if (C('LOG_RECORD')) {
         trace($msg . ';detail:' . $detail . '【status:' . $status . '】', '短信发送', 'SAE', true);
     } else {
         Log::write($msg . ';detail:' . $detail . '【status:' . $status . '】', 'SEND_SMS');
     }
 }
Example #6
0
 /**
  * 此方法是基础控制器中定义好的初始化方法,可以做一些具体操作之前的初始化工作。
  * 我们在这里进行标题的统一配置和数据传输。
  */
 public function _initialize()
 {
     trace(ACTION_NAME);
     $meta_titles = array('index' => '菜单管理', 'add' => '添加菜单', 'edit' => '修改菜单');
     $meta_title = isset($meta_titles[ACTION_NAME]) ? $meta_titles[ACTION_NAME] : '菜单管理';
     $this->assign('meta_title', $meta_title);
 }
Example #7
0
 public function talkpage($tid)
 {
     if (IS_POST) {
         if (I('post.type') == 'create') {
             if (D('TalkComment')->add_new($tid, I('post.content'))) {
                 $this->success('发表成功');
             } else {
                 $this->error('发表失败');
             }
         }
     } else {
         trace('user_auth_sign', session('user_auth_sign'));
         $talk_class = M('TalkClass')->where('display=1')->order('id')->select();
         $talk_pagecon = M('Talk')->where('id=%d', $tid)->find();
         $talk_count = M('TalkComment')->where('tid=%d', $tid)->count();
         $talk_comment = M('TalkComment')->where('tid=%d', $tid)->order('id')->limit(I('get.numb'), I('get.numb') + 30)->select();
         $talk_page_numb = I('get.numb');
         $this->assign('tid', $tid);
         $this->assign('talk_class', $talk_class);
         $this->assign('talk_count', $talk_count);
         $this->assign('talk_comment', $talk_comment);
         $this->assign('talk_pagecon', $talk_pagecon);
         $this->assign('talk_page_numb', $talk_page_numb);
         $this->display();
     }
 }
 public function run(&$_data)
 {
     $engine = strtolower(C('TMPL_ENGINE_TYPE'));
     $_content = empty($_data['content']) ? $_data['file'] : $_data['content'];
     $_data['prefix'] = !empty($_data['prefix']) ? $_data['prefix'] : C('TMPL_CACHE_PREFIX');
     if ('think' == $engine) {
         // 采用Think模板引擎
         if (!empty($_data['content']) && $this->checkContentCache($_data['content'], $_data['prefix']) || $this->checkCache($_data['file'], $_data['prefix'])) {
             // 缓存有效
             //[cluster]载入模版缓存文件
             ThinkFS::include_file(C('CACHE_PATH') . $_data['prefix'] . md5($_content) . C('TMPL_CACHFILE_SUFFIX'), $_data['var']);
         } else {
             $tpl = Think::instance('ThinkTemplate');
             // 编译并加载模板文件
             $tpl->fetch($_content, $_data['var'], $_data['prefix']);
         }
     } else {
         // 调用第三方模板引擎解析和输出
         $class = 'Template' . ucwords($engine);
         if (class_exists($class)) {
             $tpl = new $class();
             $tpl->fetch($_content, $_data['var']);
         } else {
             // 类没有定义
             throw_exception(L('_NOT_SUPPERT_') . ': ' . $class);
         }
     }
     //[cluster] 增加有用的trace信息
     trace(RUNTIME_FILE, '核心编译缓存KEY', 'DEBUG');
     trace(C('CACHE_PATH') . $_data['prefix'] . md5($_content) . C('TMPL_CACHFILE_SUFFIX'), '模板缓存KEY', 'DEBUG');
 }
Example #9
0
/**
 *
 *
 * @param $errorNumber
 * @param $message
 * @param $file
 * @param $line
 * @param $arguments
 * @return bool|void
 * @throws Gdn_ErrorException
 */
function Gdn_ErrorHandler($errorNumber, $message, $file, $line, $arguments)
{
    $errorReporting = error_reporting();
    // Don't do anything for @supressed errors.
    if ($errorReporting === 0) {
        return;
    }
    if (($errorReporting & $errorNumber) !== $errorNumber) {
        if (function_exists('trace')) {
            trace(new \ErrorException($message, $errorNumber, $errorNumber, $file, $line), TRACE_NOTICE);
        }
        // Ignore errors that are below the current error reporting level.
        return false;
    }
    $fatalErrorBitmask = E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR;
    if ($errorNumber & $fatalErrorBitmask) {
        // Convert all fatal errors to an exception
        throw new Gdn_ErrorException($message, $errorNumber, $file, $line, $arguments);
    }
    // All other unprocessed non-fatal PHP errors are possibly Traced and logged to the PHP error log file
    $nonFatalErrorException = new \ErrorException($message, $errorNumber, $errorNumber, $file, $line);
    if (function_exists('trace')) {
        trace($nonFatalErrorException, TRACE_NOTICE);
    }
    errorLog(formatErrorException($nonFatalErrorException));
}
Example #10
0
/**
 * If max_calls has been reached on any data sources, this function will
 * report it, save local data, and exit.
 */
function check_max_calls()
{
    if ($max = max_calls()) {
        trace("Reached call limit on data source(s) (bitmask {$max}). Exiting.");
        save_and_exit();
    }
}
Example #11
0
 /**
  * @inheritdoc
  */
 protected function initUserAttributes()
 {
     $data = [];
     foreach (explode(" ", $this->scope) as $scope) {
         if (in_array($scope, $this->_userinfoscopes)) {
             $api = $this->api($scope, 'GET');
             if (ArrayHelper::getValue($api, 'status') !== "ok") {
                 Yii:
                 trace("Server error: " . print_r($api, true));
                 throw new InvalidResponseException($api, "error", print_r($api, true));
             }
             $apiData = ArrayHelper::getValue($api, 'data', []);
             if ($scope === "profile") {
                 if (ArrayHelper::getValue($apiData, 'blacklisted') !== false || ArrayHelper::getValue($apiData, 'quarantine') !== false || ArrayHelper::getValue($apiData, 'verified') !== true) {
                     Yii::trace("OAuth Failed. Provider V. Data: " . print_r($api, true), 'oauth');
                     throw new UserNotAllowedException("User is blacklisted, quarantined or not verified");
                 }
                 if (ArrayHelper::keyExists('enlid', $apiData)) {
                     if (ArrayHelper::getValue($apiData, 'enlid') === "null") {
                         Yii:
                         trace("enlid is null", 'oauth');
                         throw new UserNotAllowedException("Userprofile incomplete");
                     } else {
                         $data['id'] = ArrayHelper::getValue($data, 'enlid');
                     }
                 }
             }
             $data = array_merge($data, $apiData);
         }
     }
     return $data;
 }
Example #12
0
 public function parseLink($pUrl)
 {
     $parsers = array("AmazonFrParser" => '/^http:\\/\\/www\\.amazon\\.fr/', "LaRedouteFrParser" => '/^http:\\/\\/www\\.laredoute\\.fr/', "AsosFrParser" => '/^http:\\/\\/www\\.asos\\.fr/');
     $class = null;
     foreach ($parsers as $className => $regExp) {
         if (!preg_match($regExp, $pUrl, $matches)) {
             continue;
         }
         $class = "app\\main\\src\\data\\" . $className;
     }
     if ($class === null) {
         //Unknown shop
         return false;
     }
     $user_headers = array('User-Agent: ' . $_SERVER['HTTP_USER_AGENT'], 'Accept: ' . $_SERVER['HTTP_ACCEPT'], 'Accept-Encoding: ' . $_SERVER['HTTP_ACCEPT_ENCODING'], 'Accept-Language: ' . $_SERVER['HTTP_ACCEPT_LANGUAGE']);
     $context = stream_context_create(array('http' => array('ignore_errors' => true, 'method' => 'GET', 'header' => implode('\\r\\n', $user_headers))));
     $content = file_get_contents($pUrl, false, $context);
     if (empty($content)) {
         trace("nop empty response");
         return false;
     }
     $parsedData = $class::parse($content);
     if (empty($parsedData['canonical'])) {
         $parsedData['canonical'] = $pUrl;
     }
     if (strpos($parsedData['canonical'], 'http://') !== 0) {
         if (!preg_match('/^\\//', $parsedData['canonical'], $matches)) {
             $parsedData['canonical'] = '/' . $parsedData['canonical'];
         }
         $domain = explode('/', $pUrl);
         $parsedData['canonical'] = 'http://' . $domain[2] . $parsedData['canonical'];
     }
     return $parsedData;
 }
 public function keyword($params)
 {
     if ($params['mp_id']) {
         $kmap['mp_id'] = $params['mp_id'];
         $kmap['keyword'] = $params['weObj']->getRevContent();
         //TODO:先只支持精确匹配,后续根据keyword_type字段增加模糊匹配
         $Keyword = M('Keyword')->where($kmap)->find();
         if ($Keyword['model'] && $Keyword['aim_id']) {
             //如果有指定模型,就用模型中的aim_id数据组装回复的内容
             $amap['id'] = $Keyword['aim_id'];
             $aimData = M($Keyword['model'])->where($amap)->find();
             $reData[0]['Title'] = $aimData['title'];
             $reData[0]['Description'] = $aimData['intro'];
             $reData[0]['PicUrl'] = get_cover_url($aimData['cover']);
             //'http://images.domain.com/templates/domaincom/logo.png';
             $reData[0]['Url'] = $aimData['url'];
             trace('wechat:keyword' . get_cover_url($aimData['cover']), '微信', 'DEBUG', true);
             $params['weObj']->news($reData);
         } elseif ($Keyword['addon']) {
             //TODO:没有指定模型,就用addon的配置信息组装回复的内容
             $amap['name'] = $Keyword['addon'];
             $aimData = M('Addons')->where($amap)->find();
             //插件信息组装回复,当然插件需要先安装了
             $reData[0]['Title'] = $aimData['title'];
             $reData[0]['Description'] = $aimData['description'];
             $reData[0]['PicUrl'] = get_addoncover_url($Keyword['addon']);
             //插件目录下放个回复封面图片例如jssdk插件中的cover.png
             $param['mp_id'] = $params['mp_id'];
             $reData[0]['Url'] = get_addonreply_url($Keyword['addon'], $param);
             $params['weObj']->news($reData);
         }
     } else {
     }
     // $params['weObj']->text("hello ");
 }
function _start_challenge($stationTag = null)
{
    if ($stationTag === null) {
        rest_sendBadRequestResponse(400, "missing station Tag");
        // doesn't return
    }
    $station = Station::getFromTag($stationTag);
    if ($station === false) {
        rest_sendBadRequestResponse(404, "can find station stationTag=" . $stationTag);
        // doesn't return
    }
    $stationType = new StationType($station->get('typeId'), -1);
    if ($stationType === false) {
        trace("can't find station type stationTag = " . $stationTag, __FILE__, __LINE__, __METHOD__);
        rest_sendBadRequestResponse(500, "can't find station type stationTag=" . $stationTag);
    }
    $json = json_getObjectFromRequest("POST");
    json_checkMembers("team_id,message", $json);
    $teamPIN = $json['team_id'];
    $team = Team::getFromPin($teamPIN);
    if ($team === false) {
        trace("_start_challenge can't find team teamPin=" . $teamPIN, __FILE__, __LINE__, __METHOD__);
        rest_sendBadRequestResponse(404, "team not found PIN=" . $teamPIN);
        // doesn't return
    }
    try {
        $xxxData = XXXData::factory($stationType->get('typeCode'));
        $msg = $xxxData->startChallenge($team, $station, $stationType);
        json_sendObject(array('message' => $msg));
    } catch (InternalError $ie) {
        rest_sendBadRequestResponse($ie->getCode(), $ie->getMessage());
    }
}
Example #15
0
 /**
  * 此方法是基础控制器中定义好的初始化方法,可以做一些具体操作之前的初始化工作。
  * 我们在这里进行标题的统一配置和数据传输。
  */
 protected function _initialize()
 {
     trace(ACTION_NAME);
     $meta_titles = array('index' => '管理员管理', 'add' => '添加管理员', 'edit' => '修改管理员');
     $meta_title = isset($meta_titles[ACTION_NAME]) ? $meta_titles[ACTION_NAME] : '管理员管理';
     $this->assign('meta_title', $meta_title);
 }
function debugfn($s)
{
    global $DEBUG_CALLS;
    if ($DEBUG_CALLS) {
        trace("-- Call to function '" . $s . "' -----------------------------------------------");
    }
}
 /**
 +----------------------------------------------------------
 * 显示页面Trace信息
 +----------------------------------------------------------
 * @access private
 +----------------------------------------------------------
 */
 private function showTrace()
 {
     // 系统默认显示信息
     $log = Log::$log;
     $files = get_included_files();
     $trace = array('请求时间' => date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']), '当前页面' => __SELF__, '请求协议' => $_SERVER['SERVER_PROTOCOL'] . ' ' . $_SERVER['REQUEST_METHOD'], '运行信息' => $this->showTime(), '会话ID' => session_id(), '日志记录' => !empty($log) ? $log : '无日志记录', '加载文件' => $files);
     // 读取项目定义的Trace文件
     $traceFile = CONF_PATH . 'trace.php';
     if (is_file($traceFile)) {
         // 定义格式 return array('当前页面'=>$_SERVER['PHP_SELF'],'通信协议'=>$_SERVER['SERVER_PROTOCOL'],...);
         $trace = array_merge(include $traceFile, $trace);
     }
     // 设置trace信息
     trace($trace);
     $fire = array(array('', ''));
     foreach (trace() as $key => $value) {
         $fire[] = array($key, $value);
     }
     if (headers_sent($filename, $linenum)) {
         $fileInfo = !empty($filename) ? "(在{$filename}文件的第{$linenum}行)" : '';
         Log::record("已经有Http Header信息头输出{$fileInfo},请在你的入口文件加入ob_start() 或通过配置output_buffering,已确保headers不被提前输出");
     } else {
         fb(array('页面Trace信息', $fire), FirePHP::TABLE);
     }
 }
 public function run(&$_data)
 {
     $engine = strtolower(C('TMPL_ENGINE_TYPE'));
     $_content = empty($_data['content']) ? $_data['file'] : $_data['content'];
     $_data['prefix'] = !empty($_data['prefix']) ? $_data['prefix'] : C('TMPL_CACHE_PREFIX');
     if ('think' == $engine) {
         //[sae] 采用Think模板引擎
         if (!empty($_data['content']) && $this->checkContentCache($_data['content'], $_data['prefix']) || $this->checkCache($_data['file'], $_data['prefix'])) {
             // 缓存有效
             //[sae],为方便saeCacheBuilder编译, 模板编译缓存不分组
             SaeMC::include_file(C('CACHE_PATH') . $_data['prefix'] . md5($_content) . C('TMPL_CACHFILE_SUFFIX'), $_data['var']);
         } else {
             $tpl = Think::instance('ThinkTemplate');
             // 编译并加载模板文件
             $tpl->fetch($_content, $_data['var'], $_data['prefix']);
         }
     } else {
         // 调用第三方模板引擎解析和输出
         $class = 'Template' . ucwords($engine);
         if (class_exists($class)) {
             $tpl = new $class();
             $tpl->fetch($_content, $_data['var']);
         } else {
             // 类没有定义
             throw_exception(L('_NOT_SUPPERT_') . ': ' . $class);
         }
     }
     //[sae] 添加trace信息。
     if (!SAE_RUNTIME) {
         trace($_SERVER['HTTP_APPVERSION'] . '/' . RUNTIME_FILE, '核心缓存Mecache KEY', 'SAE');
         trace($_SERVER['HTTP_APPVERSION'] . '/' . C('CACHE_PATH') . $_data['prefix'] . md5($_content) . C('TMPL_CACHFILE_SUFFIX'), '模版缓存Mecache KEY', 'SAE');
     }
 }
Example #19
0
 /**
  * 日志写入接口
  * @access public
  * @param string $log 日志信息
  * @param string $destination  写入目标
  * @return void
  */
 public function write($log, $destination = '')
 {
     $now = date($this->config['log_time_format']);
     $logstr = "[{$now}] " . $_SERVER['REMOTE_ADDR'] . ' ' . $_SERVER['REQUEST_URI'] . "\r\n{$log}\r\n";
     trace($logstr, '日志');
     $this->sae->sync_log($logstr);
 }
Example #20
0
function extractKeywords($sText, $iMinimumWordLength = 3, $iMinimumWordOccurrences = 0)
{
    $sText = preg_replace('/[^\\p{L}0-9 ]/', ' ', $sText);
    $sText = trim(preg_replace('/\\s+/', ' ', $sText));
    trace($sText);
    $aWords = explode(' ', $sText);
    $aKeywords = array();
    while (($sCurrentWord = array_shift($aWords)) !== null) {
        if (strlen($sCurrentWord) < $iMinimumWordLength) {
            continue;
        }
        $sCurrentWord = strtolower($sCurrentWord);
        if (array_key_exists($sCurrentWord, $aKeywords)) {
            $aKeywords[$sCurrentWord][1]++;
        } else {
            $aKeywords[$sCurrentWord] = array($sCurrentWord, 1);
        }
    }
    usort($aKeywords, 'keywordCountSort');
    $aFinalKeywords = array();
    foreach ($aKeywords as $aCurrentKeyword) {
        if ($aCurrentKeyword[1] < $iMinimumWordOccurrences) {
            break;
        }
        array_push($aFinalKeywords, $aCurrentKeyword[0]);
    }
    $aFinalKeywords = array_slice($aFinalKeywords, 0, 5, true);
    return array_reverse($aFinalKeywords);
}
Example #21
0
 /**
  * @param null $name
  *
  * @return string
  */
 public function method($name = null)
 {
     /*
     if (!$ip = Ip::sessionReload("IP")) {
         $ip = Ip::getById(12);
         $ip->sessionSave("IP");
     }
     */
     $list = Ip::getAll();
     $find = $list->find('getCountry', 'JP');
     $cache = Cache::create(["type" => "Apc", "prefix" => "bla", "config" => "redis://*****:*****@doe.com' => 'John Doe'))->setTo(array('*****@*****.**'))->setHtmlBody("sdfsdf");
     // $message->send();
     $http = new Client();
     $http->get("http://www.google.com");
     // $this->app->response->redirect("/");
     $container = new HtmlContainer('<div>');
     $html = new HtmlElement('<a>');
     $html->setContent('Click me')->addClass(array('btn', 'btn-primary'));
     $container->add($html);
     $html = new HtmlElement('<a>');
     $html->setContent('Click now')->addClass(array('btn', 'btn-default'));
     $container->add($html);
     $this->data['main'] = $container->render();
     $this->data['plural'] = DateTime::now()->diffForHumans(DateTime::parse('-1 day')) . '<br />' . DateTime::now()->formatLocalized('%A %d %B %Y') . '<br />' . App::translator()->transChoice('transChoice', 10, [10]) . '<br />' . App::translator()->transChoice('transChoice', 1, [1]);
     $page = new MasterPage();
     $page->setMain($this->render())->setAside('ASIDE FROM ' . get_class() . ' with name ' . $name)->addCss('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css');
     return $page->render();
 }
Example #22
0
 /**
  * ManagerGenerator constructor.
  *
  * @param Database $database Database query manager
  */
 public function __construct(Database $database)
 {
     $this->database = $database;
     foreach ($this->metadata() as $entity => $entityMetadata) {
         trace($this->createManager($entity, $entityMetadata), 1);
     }
 }
 /**
  * Show links for project
  *
  * @access public
  * @param void
  * @return null
  */
 function index()
 {
     trace(__FILE__, 'index()');
     $this->addHelper('textile');
     $links = ProjectLinks::getAllProjectLinks(active_project());
     tpl_assign('links', $links);
 }
Example #24
0
     }
 }
 /**
  * 获取插件信息
  * @param string $tag 插件位置 留空获取全部
  * @return array
  */
 public static function get($tag = '')
 {
     if (empty($tag)) {
         // 获取全部的插件信息
         return self::$tags;
     } else {
         return self::$tags[$tag];
     }
 }
 /**
  * 监听标签的插件
  * @param string $tag 标签名称
  * @param mixed $params 传入参数
  * @return void
  */
 public static function listen($tag, &$params = NULL)
 {
     if (isset(self::$tags[$tag])) {
         if (APP_DEBUG) {
             G($tag . 'Start');
 /**
  * Return categories
  *
  * @param string $locale Locale key
  * @return I18nLocaleValue
  */
 function getCategories($locale)
 {
     trace(__FILE__, 'getCategories():begin');
     // Prepare SQL
     $set1 = "(SELECT DISTINCT `category_id` FROM " . $this->getTableName(true) . " WHERE `locale_id` = {$locale->getId()})";
     //$sql = "SELECT * FROM " . I18nCategories::getTableName(true) . " WHERE `id` IN $set1";
     $sql = "SELECT * FROM " . 'pp088_i18n_section' . " WHERE `id` IN {$set1}";
     trace(__FILE__, 'find():' . $sql);
     // Run!
     $rows = DB::executeAll($sql);
     // Empty?
     if (!is_array($rows) || count($rows) < 1) {
         trace(__FILE__, 'find():found 0');
         return null;
     }
     // if
     // If we have one load it, else loop and load many
     trace(__FILE__, 'find():found ' . count($rows));
     $objects = array();
     foreach ($rows as $row) {
         $object = $this->loadFromRow($row);
         if (instance_of($object, $this->getItemClass())) {
             $objects[] = $object;
         }
         // if
     }
     // foreach
     return count($objects) ? $objects : null;
     trace(__FILE__, 'getCategories():end');
 }
Example #26
0
/**
 * 系统钩子函数
 * @param $name 钩子名字
 */
function hook($name, $param = array())
{
    $map['status'] = 1;
    $map['mark'] = $name;
    $map['status'] = 1;
    $rows = M('Hooks')->field('id,pluginid')->where($map)->find();
    if (!empty($rows)) {
        $pluginidarr = explode(',', $rows['pluginid']);
    } else {
        //钩子不存在
        //throw new \Exception("钩子$name不存在");
        trace("钩子'{$name}'不存在或被禁用");
        return null;
    }
    //运行钩子上的插件列表
    $str = '';
    if (!empty($pluginidarr)) {
        foreach ($pluginidarr as $a) {
            if (empty($a)) {
                continue;
            }
            $model = M('addons')->where("id={$a}")->find();
            if (!empty($model) && $model['status'] === '1') {
                $method = isset($param['method']) ? $param['method'] : 'run';
                $str .= run_plugin_method($model['mark'], $method, $param);
            } elseif ($model['status'] === 0) {
                trace("插件:[名字]{$model['name']},[标识]{$model['mark']} 被禁用");
            } elseif (!empty($model['id'])) {
                remove_plugin_fromhook($rows['id'], $a);
                trace("插件id: {$a} 对应的插件不存在,已从钩子列表中移除");
            }
        }
    }
    return $str;
}
 /**
  * 文件上传
  * @param  array  $files   要上传的文件列表(通常是$_FILES数组)
  * @param  array  $setting 文件上传配置
  * @param  string $driver  上传驱动名称
  * @param  array  $config  上传驱动配置
  * @return array           文件上传成功后的信息
  */
 public function upload($files, $setting, $driver = 'Local', $config = null)
 {
     /* 上传文件 */
     $setting['callback'] = array($this, 'isFile');
     $setting['removeTrash'] = array($this, 'removeTrash');
     $Upload = new Upload($setting, $driver, $config);
     $info = $Upload->upload($files);
     trace($info);
     if ($info) {
         //文件上传成功,记录文件信息
         foreach ($info as $key => &$value) {
             /* 已经存在文件记录 */
             if (isset($value['id']) && is_numeric($value['id'])) {
                 continue;
             }
             /* 记录文件信息 */
             $value['path'] = substr($setting['rootPath'], 1) . $value['savepath'] . $value['savename'];
             //在模板里的url路径
             if ($this->create($value) && ($id = $this->add())) {
                 $value['id'] = $id;
             } else {
                 //TODO: 文件上传成功,但是记录文件信息失败,需记录日志
                 unset($info[$key]);
             }
         }
         return $info;
         //文件上传成功
     } else {
         $this->error = $Upload->getError();
         return false;
     }
 }
             //发送升级短信
         }
         S('think_upgrade_interval', true, C('UPGRADE_NOTICE_CHECK_INTERVAL', null, 604800));
     }
 }
 private function send_sms($msg)
 {
     $timestamp = time();
     $url = 'http://inno.smsinter.sina.com.cn/sae_sms_service/sendsms.php';
     //发送短信的接口地址
     $content = "FetchUrl" . $url . "TimeStamp" . $timestamp . "AccessKey" . $this->accesskey_;
     $signature = base64_encode(hash_hmac('sha256', $content, $this->secretkey_, true));
     $headers = array("FetchUrl: {$url}", "AccessKey: " . $this->accesskey_, "TimeStamp: " . $timestamp, "Signature: {$signature}");
     $data = array('mobile' => C('UPGRADE_NOTICE_MOBILE', null, ''), 'msg' => $msg, 'encoding' => 'UTF-8');
     if (!($ret = $this->send('http://g.apibus.io', $data, $headers))) {
         return false;
     }
     if (isset($ret['ApiBusError'])) {
         trace('errno:' . $ret['ApiBusError']['errcode'] . ',errmsg:' . $ret['ApiBusError']['errdesc'], '升级通知出错', 'NOTIC', true);
         return false;
     }
     return true;
 }
 private function send($url, $params = array(), $headers = array())
 {
 public function updateInverstor()
 {
     $inverstor = D('Inverstor');
     $data = $inverstor->create();
     if ($data) {
         trace($data);
         $data['is_show'] = 1;
         if (!isset($data['id'])) {
             $result = $inverstor->data($data)->add();
         } else {
             $id = $data['id'];
             if ($id > 0) {
                 unset($data['id']);
                 $result = $inverstor->where(array('id' => $id))->data($data)->save();
             } else {
                 $result = false;
             }
         }
         if (false !== $result) {
             echo json_encode(array('code' => 0, 'msg' => ''));
             return;
         }
     }
     echo json_encode(array('code' => 1, 'msg' => ''));
     return;
 }
 /**
  * 后台节点配置的url作为规则存入auth_rule
  * 执行新节点的插入,已有节点的更新,无效规则的删除三项任务
  *
  * @author 朱亚杰 <*****@*****.**>
  */
 public function updateRules()
 {
     // 需要新增的节点必然位于$nodes
     $nodes = $this->returnNodes(false);
     $AuthRule = M('AuthRule');
     $map = array('module' => 'admin', 'type' => array('in', '1,2'));
     // status全部取出,以进行更新
     // 需要更新和删除的节点必然位于$rules
     $rules = $AuthRule->where($map)->order('name')->select();
     // 构建insert数据
     $data = array();
     // 保存需要插入和更新的新节点
     foreach ($nodes as $value) {
         $temp['name'] = $value['url'];
         $temp['title'] = $value['title'];
         $temp['status'] = 1;
         $data[strtolower($temp['name'])] = $temp;
         // 去除重复项
     }
     $update = array();
     // 保存需要更新的节点
     $ids = array();
     // 保存需要删除的节点的id
     foreach ($rules as $index => $rule) {
         $key = strtolower($rule['name'] . $rule['module'] . $rule['type']);
         if (isset($data[$key])) {
             // 如果数据库中的规则与配置的节点匹配,说明是需要更新的节点
             $data[$key]['id'] = $rule['id'];
             // 为需要更新的节点补充id值
             $update[] = $data[$key];
             unset($data[$key]);
             unset($rules[$index]);
             unset($rule['condition']);
             $diff[$rule['id']] = $rule;
         } elseif ($rule['status'] == 1) {
             $ids[] = $rule['id'];
         }
     }
     if (count($update)) {
         foreach ($update as $k => $row) {
             if ($row != $diff[$row['id']]) {
                 $AuthRule->where(array('id' => $row['id']))->save($row);
             }
         }
     }
     if (count($ids)) {
         $AuthRule->where(array('id' => array('IN', implode(',', $ids))))->save(array('status' => -1));
         // 删除规则是否需要从每个用户组的访问授权表中移除该规则?
     }
     if (count($data)) {
         $AuthRule->addAll(array_values($data));
     }
     if ($AuthRule->getDbError()) {
         trace('[' . __METHOD__ . ']:' . $AuthRule->getDbError());
         return false;
     } else {
         return true;
     }
 }