Beispiel #1
0
 public function resolve(Request $request, Response $response)
 {
     $pathInfo = $request->uri('path');
     // Inex 1 because request URI starts with a slash
     if (strpos($pathInfo, $this->dstPath) !== 1) {
         return;
     } else {
         $pathInfo = substr($pathInfo, strlen($this->dstPath) + 1);
     }
     $pathInfo = pathinfo($pathInfo);
     // Only serves .min.css requests
     if (!preg_match('/\\.min\\.css$/', $pathInfo['basename'])) {
         return;
     }
     $pathInfo['filename'] = preg_replace('/\\.min$/', '', $pathInfo['filename']);
     $_srcPath = "/{$pathInfo['dirname']}/{$pathInfo['filename']}.css";
     $dstPath = "./{$this->dstPath}/{$pathInfo['dirname']}/{$pathInfo['filename']}.min.css";
     foreach ($this->srcPath as $srcPath) {
         $srcPath = "./{$srcPath}{$_srcPath}";
         // compile when: target file not exists, or source is newer
         if (file_exists($srcPath) && (!file_exists($dstPath) || @filemtime($srcPath) > @filemtime($dstPath))) {
             // empty results are ignored
             $result = trim(@CssMin::minify(file_get_contents($srcPath)));
             if ($result && !@file_put_contents($dstPath, $result)) {
                 Log::warn('Permission denied, unable to minify CSS.');
             }
             break;
         }
     }
 }
Beispiel #2
0
 public function resolve(Request $request, Response $response)
 {
     $pathInfo = $request->uri('path');
     // Inex 1 because request URI starts with a slash
     if (strpos($pathInfo, $this->dstPath) !== 1) {
         return;
     } else {
         $pathInfo = substr($pathInfo, strlen($this->dstPath) + 1);
     }
     $pathInfo = pathinfo($pathInfo);
     // Only serves .css requests
     if ($pathInfo['extension'] != 'css') {
         return;
     }
     // also takes care of .min requests
     $pathInfo['filename'] = preg_replace('/\\.min$/', '', $pathInfo['filename']);
     $_srcPath = "/{$pathInfo['dirname']}/{$pathInfo['filename']}.scss";
     $dstPath = "./{$this->dstPath}/{$pathInfo['dirname']}/{$pathInfo['filename']}.css";
     foreach ($this->srcPath as $srcPath) {
         $srcPath = "./{$srcPath}{$_srcPath}";
         // compile when: target file not exists, or source is newer
         if (!file_exists($dstPath) || @filemtime($srcPath) > @filemtime($dstPath)) {
             $result = @trim((new Compiler())->compile(file_get_contents($srcPath)));
             // note; write empty file if target exists
             if ($result || file_exists($dstPath)) {
                 if (!@file_put_contents($dstPath, $result)) {
                     Log::warn('Permission denied, unable to compile SCSS.');
                 }
             }
             break;
         }
     }
 }
 function resolve(Request $request, Response $response)
 {
     if ($response->status() != 200) {
         return;
         // only normal response will be processed
     }
     foreach ((array) $request->meta('output') as $outputFilter) {
         // format: func([param1[,param2[,param3 ...]]])
         if (preg_match('/(\\w+)\\(([\\w\\s,]*)\\)/', $outputFilter, $matches)) {
             $func = @$this->funcMap[$matches[1]];
             if (is_callable($func)) {
                 if (@$matches[2]) {
                     $func = call_user_func_array($func, explode(',', $matches[2]));
                 }
                 if (is_callable($func)) {
                     try {
                         $response->send(call_user_func_array($func, array($response->body())));
                     } catch (\Exception $e) {
                         Log::error(sprintf('[InvokerPostProcessor] Error calling %s(): %s @ %s:%d', $matches[1], $e->getMessage(), basename($e->getFile()), $e->getLine()), $e->getTrace());
                         $response->send(array('error' => $e->getMessage(), 'code' => $e->getCode()), 500);
                     }
                 }
             }
         }
     }
 }
 function process()
 {
     $path = (array) @$this->taskInstance()->settings;
     $path = $path['path'];
     $store = $this->dataStore();
     Log::info(sprintf('Value of (%s) in current data store.', $path), array('path' => $path, 'value' => util::deepVal($path, $store)));
 }
Beispiel #5
0
 public function __destruct()
 {
     if ($this->v2Support) {
         $_SESSION['__pmg.request'] = serialize($this);
     }
     /* Log the request */
     Log::logRequest($this);
 }
Beispiel #6
0
 public static function addJob($id, $function, $data)
 {
     $client = new \GearmanClient();
     $client->addServer(gearman_server, gearman_port);
     $job = new Job();
     $job->setId($id)->setExpireTime(time() + 172800)->setReference(array('CLIController', $function, $data));
     $job_handle = $client->doBackground(app_name . 'handle', serialize($job));
     Log::write(__METHOD__ . ' invoked gearman job (' . $function . ') for id ' . $id . ' ' . app_name . 'handle' . ' ' . $client->returnCode());
 }
Beispiel #7
0
 /**
  * 404 Error Handler
  *
  * @uses	MyException::show_error()
  *
  * @param	string	$page		Page URI
  * @param 	bool	$log_error	Whether to log the error
  * @return	void
  */
 public function show_404($page = '', $log_error = TRUE)
 {
     $heading = '404 Page Not Found';
     $message = 'The page you requested was not found.';
     if ($log_error) {
         \Core\Log::write('error', $heading . ': ' . $page, '404');
     }
     $this->show_error($heading, $message, 'error_404', 404);
 }
 public function run()
 {
     $user_list = config('user_list') ? config('user_list') : array();
     $date = date("Y-m-d");
     $user_check = array();
     for (;;) {
         foreach ($user_list as $user => $user_info) {
             $log_head = date("H:i:s") . ':' . $user . '--';
             $check = isset($user_check[$user]) ? $user_check[$user] : FALSE;
             if (!$check) {
                 $baidu = new BaiduAction($user, $user_info['password']);
                 $tieba = new TiebaAction($baidu->getCookie());
                 $result = $tieba->sign();
                 if ($result) {
                     foreach ($result as $key => $value) {
                         $result_info = implode(';', $result[$key]);
                         switch ($key) {
                             case 'success':
                                 $info = '以下贴吧签到成功:';
                                 break;
                             case 'repeat':
                                 $info = '以下贴吧已经签到:';
                                 break;
                             case 'ban':
                                 $info = '以下贴吧已被封:';
                                 break;
                             case 'error':
                                 $info = '以下贴吧签到失败:';
                                 break;
                             default:
                                 break;
                         }
                         Log::log($log_head . $info . $result_info . ENTER);
                     }
                     if ($tieba->success_count + $tieba->repeat_count + $tieba->ban_count == $tieba->num) {
                         Log::log($log_head . '本日全部贴吧签到完成。' . ENTER);
                         $user_check[$user] = TRUE;
                         //完成标记
                     }
                 } else {
                     $info = 'COOKIE错误,可能需要验证码登录。--';
                     Log::log($log_head . $info);
                     Log::log(Email::send($user_info['email'], $user, $info) . ENTER);
                     unlink(COOKIE_PATH . '/' . md5($user));
                 }
                 Log::save();
                 //保存日志
                 $date = date("Y-m-d");
             }
             if ($date != date("Y-m-d")) {
                 $user_check[$user] = FALSE;
             }
             //重置完成状态
         }
         sleep(mt_rand(config('min_time'), config('max_time')));
     }
 }
Beispiel #9
0
 public function delete()
 {
     if ($this->status) {
         $list = array_flip(array_flip(func_get_args()));
         foreach ($list as $v) {
             $path = $this->root . $v;
             if (is_file($path) && is_writable($path)) {
                 if (!unlink($path)) {
                     Log::write(_("Image file delete fail:") . $path);
                 }
             }
         }
     } else {
     }
 }
Beispiel #10
0
 public function resolve(Request $request, Response $response)
 {
     global $argv;
     // Debug access log
     if (System::environment() == 'debug') {
         switch ($request->client('type')) {
             case 'cli':
                 $message = implode(' ', array($request->client('type'), $request->uri()));
                 break;
             default:
                 $message = implode(' ', array($request->client('version'), strtoupper($request->method()), $request->uri('path')));
                 @Log::debug($message, array_filter(array('origin' => $request->client('referer'), 'userAgent' => util::cascade(@$request->client('userAgent'), 'Unknown'), 'timeElapsed' => round(microtime(1) - $request->timestamp(), 4) . ' secs')));
                 break;
         }
     }
 }
Beispiel #11
0
 /**
  * 自定义错误处理机制
  * @param int 错误代码
  * @param string 错误信息
  * @param string 错误文件
  * @param int 错误行号
  * @return void
  */
 public static function appError($errno, $errstr, $errfile, $errline)
 {
     // 错误记录
     Log::error($error[$errno], $errstr, $errfile, $errline);
     // 服务器错误
     Response::_500();
 }
Beispiel #12
0
 public function __destruct()
 {
     if ($this->log === true) {
         if (!empty($this->_sql)) {
             \Core\Log::write($this->_sql, 'SQL');
         }
     }
 }
Beispiel #13
0
//
//  Logger initialization
//
//------------------------------------------------------------------------------
/*! Note @ 7 Aug, 2015
 *  Here we started to make use of the Psr\Log interface and Seldaek\Monolog,
 *  digging the original Log class empty as a wrapper to LoggerInterface, and
 *  moved the backtrace and session info into separate processors in monolog.
 *
 *  Specifically, backtrace context like file, subject and action are moved to
 *  the BacktraceProcessor class, while session info is moved to the
 *  SessionProcessor class.
 *
 *  Node::set() invoke is migrated into NodeHandler class.
 */
Log::setLogger(new Logger('default'));
// Log enabled
if (conf::get('system::log.enabled', true)) {
    $level = Logger::toMonologLevel(conf::get('system::log.level', 'debug'));
    Log::getLogger()->pushProcessor(new BacktraceProcessor($level))->pushProcessor(new SessionProcessor($level))->pushProcessor(new ProcessProcessor($level))->pushHandler(new NodeHandler($level));
    unset($level);
} else {
    // This should not be necessary, no handlers will run nothing.
    Log::getLogger()->pushHandler(new NullHandler());
}
//------------------------------------------------------------------------------
//
//  System shims
//
//------------------------------------------------------------------------------
require_once __DIR__ . '/framework/environment.php';
Beispiel #14
0
 /**
  * @param array $list
  */
 private function getListDataParse(&$list)
 {
     if ($list === false) {
         Log::write(_("Get comment list of user error."), Log::SQL);
         $this->throwMsg(-2);
     }
     $ol = [];
     for ($i = 0, $l = count($list); $i < $l; ++$i) {
         $ol[$list[$i][$this->type . "_id"]] = $list[$i][$this->type . "_id"];
     }
     $info = $this->cm->getCommentTypeInfo($this->type, $ol);
     for ($i = 0, $l = count($list); $i < $l; ++$i) {
         if (isset($info[$list[$i][$this->type . "_id"]])) {
             $list[$i]['info'] =& $info[$list[$i][$this->type . "_id"]];
         } else {
             //此处数据出错,或者数据不完整
             Log::write(_("Data loss on CommentList class."), Log::NOTICE);
             unset($list[$i]);
         }
     }
 }
Beispiel #15
0
<?php

/*! HeadlessWorker.php | Takes care of headless process ahead. */
require_once '.private/scripts/Initialize.php';
use core\Database;
use core\Log;
use framework\Bayeux;
use framework\Configuration as conf;
use framework\Service;
use models\WorkInstance;
use models\TaskInstance;
$taskInstance = new TaskInstance();
// Consumes Headless tasks ahead.
$tasks = Database::fetchArray('SELECT `nextTask` FROM `WorkInstance`
  WHERE `nextTask` IN (SELECT `uuid` FROM `TaskInstance` WHERE `type` = \'Headless\')
    AND `state` = \'Open\';');
$tasks = array_map(compose('core\\Utility::unpackUuid', prop('nextTask')), $tasks);
if ($tasks) {
    Log::debug(sprintf('%d headless tasks found!', count($tasks)), $tasks);
}
$serviceOptions = array('resolver' => new framework\Resolver());
$serviceOptions['resolver']->registerResolver(new resolvers\WebServiceResolver(array('prefix' => conf::get('web::resolvers.service.prefix', '/service'))));
foreach ($tasks as $taskUuid) {
    // renew response object for each call
    $serviceOptions['response'] = new framework\Response(array('autoOutput' => false));
    Service::call('_/WorkInstance', 'process', array($taskUuid), $serviceOptions);
    // todo: send bayeux update message to notify related users about the task update.
}
Beispiel #16
0
// Log the process output if available
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
if ("{$stdout}{$stderr}") {
    $method = $stderr ? 'error' : 'info';
    Log::$method(sprintf('Output captured from command line: %s', $process['command']), array_filter(array('stdout' => $stdout, 'stderr' => $stderr)));
    unset($method);
}
unset($stdout, $stderr);
// Handles cleanup after process exit
switch (strtolower($process['type'])) {
    // Permanent processes will be restarted upon death
    case 'permanent':
        core\Database::query('UPDATE `' . FRAMEWORK_COLLECTION_PROCESS . '` SET `pid` = NULL WHERE `id` = ?', $process['id']);
        Log::debug('Permanent process died, clearing pid.', [$res, $process]);
        break;
        // Sets pid to 0, prevents it fire again and double enqueue of the same time slot.
    // Sets pid to 0, prevents it fire again and double enqueue of the same time slot.
    case 'cron':
        core\Database::query('UPDATE `' . FRAMEWORK_COLLECTION_PROCESS . '` SET `pid` = 0 WHERE `id` = ?', $process['id']);
        break;
        // Deletes the process object upon exit
    // Deletes the process object upon exit
    default:
        $process = array_select($process, array(Node::FIELD_COLLECTION, 'id', 'pid'));
        $res = Node::delete($process);
        Log::debug("Deleting finished process, affected rows: {$res}.", [$res, $process]);
        break;
}
// Recursive process, spawn another worker.
Process::spawnWorker(@$_SERVER['env']);
Beispiel #17
0
 public function update($title, $name, $content, $category, $keyword, $description, $status, $allow_comment, $user_id)
 {
     if (!$this->existsCheck($this->post_id, $user_id)) {
         $this->throwMsg(-5);
     }
     $title = trim($title);
     $name = trim($name);
     $content = trim($content);
     $this->checkTitle($title);
     $this->checkName($name);
     if ($this->existsName($name, $this->post_id)) {
         $this->throwMsg(-9);
     }
     if (empty($content)) {
         $this->throwMsg(-8);
     }
     if (!in_array($category, $this->getCategory())) {
         $this->throwMsg(-10);
     }
     if ($status < 0 || $status > 1) {
         $this->throwMsg(-11);
     }
     $data = ['post_name' => $name, 'post_title' => $title, 'post_content' => $content, 'post_category' => $category, 'post_keyword' => $keyword, 'post_description' => $description, 'post_status' => $status, 'post_update_time' => date("Y-m-d H:i:s"), 'post_allow_comment' => $allow_comment > 0 ? 1 : 0];
     if ($this->db->update('posts', $data, ['id' => $this->post_id]) < 0) {
         Log::write(_("Update post error.") . Log::SQL);
         $this->throwMsg(-12);
     }
 }
Beispiel #18
0
    /**
     * 检测用户,根据字符串数组
     * @param string[] $list
     * @param int      $u_id
     * @return int[]
     */
    private function checkUser($list, $u_id)
    {
        $list = array_flip(array_flip($list));
        if (count($list) > 10) {
            $this->throwMsg(-5);
        }
        $ss = $this->db->select("users", ['id'], ['user_name' => $list]);
        $list = [];
        foreach ($ss as $v) {
            $list[] = intval($v['id']);
        }
        if (count($list) < 1) {
            return [];
        }
        if ($u_id !== 0) {
            $ss = implode(",", $list);
            $sql = <<<EOM
SELECT `users_id`, `follow_users_id` FROM `users_follow_users` WHERE
(`users_id` = {$u_id} AND `follow_users_id` in ({$ss}))
OR
(`users_id` in ({$ss}) AND `follow_users_id` = {$u_id});
EOM;
            $stmt = $this->db->getReader()->query($sql);
            if ($stmt === false) {
                Log::write(_("Get sql message users error."), Log::SQL);
                $this->throwMsg(-8);
            }
            $ss = $stmt->fetchAll(\PDO::FETCH_ASSOC);
            unset($stmt);
            $list = [];
            foreach ($ss as $v) {
                if (!isset($list[$v['users_id']])) {
                    $list[$v['users_id']] = intval($v['users_id']);
                }
                if (!isset($list[$v['follow_users_id']])) {
                    $list[$v['follow_users_id']] = intval($v['follow_users_id']);
                }
            }
            if (isset($list[$u_id])) {
                unset($list[$u_id]);
            }
        }
        return $list;
    }
Beispiel #19
0
 /**
  * 构造方法,使用评论的信息和对应的用户类
  * @param array $set_info
  * @param int   $user_id
  */
 function __construct($set_info, $user_id)
 {
     $this->ip_c = Ip::getInstance();
     $this->user = User::getUser($user_id);
     if (is_array($set_info) && isset($set_info['comment_id'])) {
         static $names = [];
         if (count($names) === 0) {
             $ref = new \ReflectionClass($this);
             foreach ($ref->getProperties() as $ro) {
                 $names[] = $ro->getName();
             }
             $names = array_flip($names);
             unset($names['ip_c'], $names['user'], $names['sub_node']);
         }
         if (isset($set_info['comment_ip'])) {
             $set_info['comment_ip'] = $this->ip_c->bin2ip($set_info['comment_ip']);
         }
         foreach ($set_info as $k => $v) {
             if (isset($names[$k])) {
                 $this->{$k} = $v;
             }
         }
         self::$comment_stack[$this->getCommentId()] = $this;
     } else {
         Log::write(_("Comment class construct error"), Log::ALERT);
     }
 }
Beispiel #20
0
 private function initUser(&$data)
 {
     $ids = [];
     foreach ($data as &$v) {
         if (!isset($ids[$v['users_id']]) && User::UserStack($v['users_id']) === false) {
             $ids[$v['users_id']] = $v['users_id'];
         }
     }
     if (reset($ids)) {
         $list = $this->db->select("users", ['id' => 'id', 'user_name' => 'name', 'user_aliases' => 'aliases', 'user_email' => 'email', 'user_url' => 'url', 'user_status' => 'status', 'user_registered_time' => 'registered_time', 'user_last_login_time' => 'last_login_time', 'user_avatar' => 'avatar'], ['id' => $ids]);
         if ($list === false) {
             Log::write(_("Select other users error."), Log::SQL);
         } else {
             foreach ($list as &$v) {
                 //保存数据到堆栈
                 new User($v, true);
             }
         }
     }
 }
Beispiel #21
0
 /**
  * 插入评论内容
  * @param string $content
  * @param int    $parent
  * @param int    $parent_top
  * @param int    $user_id
  * @return int
  */
 private function insert_comment($content, $parent, $parent_top, $user_id)
 {
     c_lib()->load('input');
     $input = new Input();
     $ip = $input->getIp()->binIp();
     $ua = $input->getUA();
     $write = $this->db->getWriter();
     $write->pdo->beginTransaction();
     $info = ['users_id' => $user_id, 'comment_content' => $content, 'comment_time' => $input->time(), 'comment_parent' => $parent ? $parent : NULL, 'comment_parent_top' => $parent_top ? $parent_top : NULL, 'comment_ip' => $ip, 'comment_agent' => $ua];
     $info['comment_status'] = $this->get_comment_status($info);
     $comment_id = $write->insert("comments", $info);
     if ($comment_id < 1) {
         $write->pdo->rollBack();
         Log::write(implode(",", $write->error()), Log::SQL);
         $this->throwMsg(-5);
     }
     $has_flag = $write->insert($this->relation_table, ['comments_id' => $comment_id, $this->relation_field => $this->id, 'users_id' => $user_id, 'object_users_id' => $this->get_object_users_id()]);
     if ($has_flag < 0) {
         $write->pdo->rollBack();
         Log::write(implode(",", $write->error()), Log::SQL);
         $this->throwMsg(-6);
     }
     $write->pdo->commit();
     $rt = $this->comment_hook($content, $parent, $parent_top, $user_id);
     if ($parent != 0) {
         hook()->apply('Comment_reply', $rt, $this->comment_type, $this->id, $user_id, $parent, $parent_top, $content);
     }
     return $comment_id;
 }
Beispiel #22
0
 private function clearOtherAvatar($avatar_name)
 {
     foreach (self::$list as $v) {
         $path = _BasePath_ . "/avatar/{$v}/" . $avatar_name;
         if (is_file($path)) {
             if (!@unlink($path)) {
                 Log::write("Delete avatar error." . $path, Log::WARN);
             }
         }
     }
 }
Beispiel #23
0
 /**
  * 获取异常信息
  * @param int $code
  * @return string
  */
 public function getMsg($code)
 {
     switch ($code) {
         case -1:
             return _("User is error.");
         case -2:
             Log::write(implode(", ", db()->error()['read']) . "\n" . db()->last_query()['read'], Log::SQL);
             return _("Data select error on sql.");
         default:
             return _("Unknown error");
     }
 }
Beispiel #24
0
 /**
  * Send HTTP request to a URL.
  *
  * The format is purposedly copied as much as possible from jQuery.ajax() function.
  *
  * To initiate multiple requests, pass it as an array and wrapping parameters of
  * each single request as an array.
  *
  * @param {string} $options['url'] Target request url
  * @param {?string} $options['type'] Request method, defaults to GET.
  * @param {?array|string} $options['data'] Either raw string or array to be encoded,
  *                                         to be sent as query string on GET, HEAD, DELETE and OPTION
  *                                         or message body on POST or PUT.
  * @param {?array} $options['headers'] Request headers to be sent.
  * @param {?callable} $options['progress'] Callback function for progress ticks.
  *                                         function($progress, $current, $maximum);
  * @param {?callable} $options['success'] Callback function on successful request.
  *                                        function($responseText, $curlOptions);
  * @param {?callable} $options['failure'] Callback function on request failure, with curl errors as parameters.
  *                                        function($errorNumber, $errorMessage, $curlOptions);
  * @param {?array} $options['__curlOpts'] Curl options to be passed directly to curl_setopt_array.
  *
  * @return void
  */
 public static function httpRequest($options)
 {
     $options = Utility::wrapAssoc((array) $options);
     $options = array_map(function (&$option) {
         if (is_string($option)) {
             $option = array('url' => $option);
         } else {
             if (!@$option['url']) {
                 throw new exceptions\CoreException('No URL set!');
             }
         }
         // Auto prepend http, default protocol.
         if (preg_match('/^(\\/\\/)/', $option['url'])) {
             $option['url'] = "http:" . $option['url'];
         }
         $curlOption = array(CURLOPT_URL => $option['url'], CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_CAINFO => null, CURLOPT_CAPATH => null, CURLOPT_FOLLOWLOCATION => true);
         // Request method: 'GET', 'POST', 'PUT', 'HEAD', 'DELETE'
         if (!isset($option['type']) && is_array(@$option['data']) || preg_match('/^post$/i', @$option['type'])) {
             $curlOption[CURLOPT_POST] = true;
             $curlOption[CURLOPT_CUSTOMREQUEST] = 'POST';
         } elseif (preg_match('/^put$/i', @$option['type'])) {
             if (!@$option['file'] || !is_file($option['file'])) {
                 throw new exceptions\CoreException('Please specify the \'file\' option when using PUT method.');
             }
             $curlOption[CURLOPT_PUT] = true;
             $curlOption[CURLOPT_CUSTOMREQUEST] = 'PUT';
             $curlOption[CURLOPT_UPLOAD] = true;
             $curlOption[CURLOPT_INFILE] = fopen($option['file'], 'r');
             $curlOption[CURLOPT_INFILESIZE] = filesize($option['file']);
         } elseif (preg_match('/^head$/i', @$option['type'])) {
             $curlOption[CURLOPT_NOBODY] = true;
             $curlOption[CURLOPT_CUSTOMREQUEST] = 'HEAD';
         } elseif (preg_match('/^delete$/i', @$option['type'])) {
             $curlOption[CURLOPT_CUSTOMREQUEST] = 'DELETE';
         } else {
             $curlOption[CURLOPT_CUSTOMREQUEST] = 'GET';
         }
         // Query data, applicable for all request methods.
         if (@$option['data']) {
             $data = $option['data'];
             // The data contains traditional file POST value: "@/foo/bar"
             $hasPostFile = is_array($data) && array_reduce($data, function ($ret, $val) {
                 return $ret || is_a($val, 'CurlFile') || is_string($val) && strpos($val, '@') === 0 && file_exists(Utility::unwrapAssoc(explode(';', substr($val, 1))));
             }, false);
             // Build query regardless if file exists on PHP < 5.2.0, otherwise
             // only build when there is NOT files to be POSTed.
             // Skip the whole build if $data is not array or object.
             if ((version_compare(PHP_VERSION, '5.2.0', '<') || !$hasPostFile) && (is_array($data) || is_object($data))) {
                 $data = http_build_query($data);
             }
             if (version_compare(PHP_VERSION, '5.5.0', '>=') && $hasPostFile) {
                 array_walk_recursive($data, function (&$value, $key) {
                     if (is_string($value) && strpos($value, '@') === 0) {
                         @(list($path, $type) = explode(';', substr($value, 1)));
                         if (!$type) {
                             $type = Utility::getInfo($path, FILEINFO_MIME_TYPE);
                         }
                         $value = curl_file_create($path, $type, $key);
                     }
                 });
             }
             if (@$curlOption[CURLOPT_POST] === true) {
                 $curlOption[CURLOPT_POSTFIELDS] = $data;
             } else {
                 $url =& $curlOption[CURLOPT_URL];
                 $url .= (strpos($url, '?') === false ? '?' : '&') . $data;
             }
         }
         // HTTP Headers
         if (isset($option['headers'])) {
             $curlOption[CURLOPT_HTTPHEADER] =& $option['headers'];
         }
         // Data type converting
         if (isset($option['success'])) {
             $originalSuccess = @$option['success'];
             switch (@$option['dataType']) {
                 case 'json':
                     $option['success'] = function ($response, $curlOptions) use($option, $originalSuccess) {
                         $result = @ContentEncoder::json($response);
                         if ($result === false && $response) {
                             Utility::forceInvoke(@$option['failure'], array(3, 'Malformed JSON string returned.', $curlOptions));
                         } else {
                             Utility::forceInvoke(@$originalSuccess, array($result, $curlOptions));
                         }
                     };
                     break;
                 case 'xml':
                     $option['success'] = function ($response, $curlOptions) use($option, $originalSuccess) {
                         try {
                             $result = XMLConverter::fromXML($response);
                         } catch (\Exception $e) {
                             $result = NULL;
                         }
                         if ($result === NULL && $response) {
                             Utility::forceInvoke(@$option['failure'], array(2, 'Malformed XML string returned.', $curlOptions));
                         } else {
                             Utility::forceInvoke(@$originalSuccess, array($result, $curlOptions));
                         }
                     };
                     break;
             }
             unset($originalSuccess);
         }
         $curlOption['callbacks'] = array_filter(array('progress' => @$option['progress'], 'success' => @$option['success'], 'failure' => @$option['failure'], 'complete' => @$option['complete']));
         $curlOption = (array) @$option['__curlOpts'] + $curlOption;
         if (System::environment() == 'debug') {
             Log::debug('Net ' . $curlOption[CURLOPT_CUSTOMREQUEST] . ' to ' . $curlOption[CURLOPT_URL], $curlOption);
         }
         return $curlOption;
     }, $options);
     return self::curlRequest($options);
 }
Beispiel #25
0
 public function delete($id, $uid)
 {
     $id = +$id;
     $uid = +$uid;
     if (!$this->db->has("feed", ['AND' => ['id' => $id, 'users_id' => $uid]])) {
         $this->throwMsg(-1);
     }
     $status = $this->db->delete("feed", ['AND' => ['id' => $id, 'users_id' => $uid]]);
     if ($status === false) {
         Log::write(_("Delete feed error."), Log::SQL);
         $this->throwMsg(-2);
     }
     if ($status != 1) {
         $this->throwMsg(-3);
     }
 }
Beispiel #26
0
 /**
  * 邮件发送
  * @param string      $name
  * @param string      $email
  * @param string|null $title
  * @param string|null $textContent
  * @param bool        $queue
  * @throws \Exception
  */
 public function mailSend($name, $email, $title = NULL, $textContent = NULL, $queue = true)
 {
     if (!hook()->apply("MailTemplate_mailSend", true)) {
         //是否取消所有邮件发送记录
         Log::write(_("Mail send is cancel.") . print_r(func_get_args(), true), Log::NOTICE);
         return;
     }
     if (!$this->is_set_values) {
         $this->setValues([]);
     }
     try {
         c_lib()->load('mail');
         $mail = new Mail();
         if ($title === NULL) {
             $title = $this->title;
         }
         $mail->Subject = $title;
         $mail->addAddress($email, $name);
         $mail->msgHTML($this->content);
         if ($textContent === NULL) {
             $mail->AltBody = $this->text;
         } else {
             $mail->AltBody = $textContent;
         }
         if (hook()->apply('MailTemplate_mailSend_noQueue', !$queue)) {
             $mail->send();
         } else {
             lib()->load('Queue');
             $queue = new Queue();
             $mail_call = new MailCallback($mail);
             $queue->add($mail_call, NULL, ['lib' => ['MailTemplate'], 'c_lib' => ['mail']]);
         }
     } catch (\Exception $ex) {
         throw new \Exception(_("Mail Send Error.") . debug(" :" . $ex->getMessage()));
     }
 }
Beispiel #27
0
 /**
  * 回复微信服务器, 此函数支持链式操作
  * Example: $this->text('msg tips')->reply();
  * @param array $msg 要发送的信息, 默认取$this->msg
  * @param bool $return 是否返回信息而不抛出到浏览器 默认:否
  * @return string
  */
 public function reply($msg = array(), $return = false)
 {
     if (empty($msg)) {
         $msg = $this->msg;
     }
     $xml = $this->xml_encode($msg);
     Log::write('reply', $xml);
     if ($return) {
         return $xml;
     } else {
         echo $xml;
     }
 }
Beispiel #28
0
 /**
  * 用户注册
  * @param $email     string 邮箱
  * @param $password  string   hash密码
  * @param $name      string 用户名
  * @param $captcha   string 验证码
  * @return int    错误代码或者用户成功注册ID
  */
 public function Register($email, $password, $name, $captcha)
 {
     $email = strtolower(trim($email));
     $password = strtolower(trim($password));
     $name = strtolower(trim($name));
     $captcha = trim($captcha);
     if (($code = hook()->apply("UserRegister_Register_before", 0, $email, $password, $name, $captcha)) < 0) {
         return $code;
     }
     if (!$this->Captcha($captcha)) {
         return -1;
     }
     if (!UserCheck::CheckPassword($password)) {
         return -2;
     }
     if (UserCheck::CheckName($name) !== true) {
         return -4;
     }
     if (UserCheck::CheckEmail($email) !== true) {
         return -5;
     }
     $ip = new Ip();
     $register_array = ['user_name' => $name, 'user_email' => $email, 'user_aliases' => $name, 'user_password' => '', 'user_salt' => salt(64), 'user_registered_time' => date("Y-m-d H:i:s"), 'user_registered_ip' => $ip->ip2bin($ip->realip()), 'user_cookie_salt' => salt(64), 'user_avatar' => UserCheck::DefaultAvatar(), 'user_status' => 0];
     $register_array['user_password'] = UserCheck::CreatePassword($password, $register_array['user_salt']);
     $reg_code = db()->insert("users", $register_array);
     if ($reg_code <= 0) {
         Log::write(_("User register insert sql error."), Log::SQL);
         return -3;
     }
     try {
         //关于注册成功的提醒
         hook()->apply("UserRegister_Register_success", $reg_code, $register_array);
         if (hook()->apply("UserRegister_Register_success_send_mail", true)) {
             //判断是否注册过程中需要发送注册邮件
             $u = new User($reg_code);
             $this->SendActivationMail($u);
         }
     } catch (\Exception $ex) {
         Log::write(_("User register success exception notice"), Log::NOTICE);
     }
     return $reg_code;
 }
Beispiel #29
0
 private function insertData(FeedInterface $object)
 {
     $content = @serialize($object);
     $sid = $object->getSid();
     $action = $object->getAction();
     if (is_string($action)) {
         $status = $this->db->insert('feed', ['action' => $action, 'content' => $content, 'sid' => $sid, 'users_id' => $object->getUserId(), 'time' => date("Y-m-d H:i:s")]);
         if ($status < 1) {
             Log::write(_("Insert feed error.") . "On " . $action, Log::SQL);
             return false;
         }
         return $status;
     }
     return false;
 }
Beispiel #30
0
 /**
  * 发送消息给关注用户
  * @param null $rt
  * @param int  $f_id 被关注ID
  * @param int  $u_id 关注者ID
  * @return null
  */
 public function message_follow_me($rt, $f_id, $u_id)
 {
     try {
         if ($this->notice($f_id, 'message', 'follow_me')) {
             $user = User::getUser($u_id);
             $follow_user = User::getUser($f_id);
             $mt = new MailTemplate("message_notice/follow_me.md");
             $mt->setUserInfo($follow_user->getInfo());
             $mt->setValues(['follow_user_aliases' => $user->getAliases(), 'follow_user_url' => user_link($user->getName()), 'follow_list_link' => get_url('Follow', 'ta'), 'follow_user_name' => $user->getName()]);
             $this->message->addNoticeMsg($mt->getTitle(), $mt->getContent(), $f_id);
         }
     } catch (\Exception $ex) {
         Log::write(_("Message to message_follow_me create a Exception.") . "EX:[" . $ex->getCode() . "]:" . $ex->getMessage(), Log::NOTICE);
     }
     return $rt;
 }