Exemplo n.º 1
0
 function createAction()
 {
     if (!$this->obj->findOne(['user' => 'admin'])) {
         $ok = $this->obj->insert(['user' => 'admin', 'pwd' => password_hash('admin', PASSWORD_DEFAULT)]);
     }
     d($ok);
 }
Exemplo n.º 2
0
 public static function sync($source, $destination, $syncTaskId = 0)
 {
     // Stats
     $stats = array('links' => 0);
     // Get source data
     $links = BackupsModel::all(array('user_id' => $source['username']['id'], 'sync_task_id' => $syncTaskId, 'entity_type' => static::$kind['link']))->toArray();
     $syncedLinks = MigratedDataModel::all(array('source_id' => $source['username']['id'], 'destination_id' => $destination['username']['id'], 'kind' => static::$kind['link']))->column('identifier');
     if ($links) {
         foreach ($links as $link) {
             if (!in_array($link['entity_id'], $syncedLinks)) {
                 $link['entity'] = json_decode($link['entity'], true);
                 $newLink = array_diff_key($link['entity'], array_flip(static::$skip['link']));
                 $newLink = \Rest::postJSON(static::$endpoints['link'], $newLink, $destination);
                 if (isset($newLink['result']['error'])) {
                     d($newLink);
                 }
                 $stats['links']++;
                 $syncedCalendar = MigratedDataModel::create();
                 $syncedCalendar->source_id = $source['username']['id'];
                 $syncedCalendar->destination_id = $destination['username']['id'];
                 $syncedCalendar->kind = static::$kind['link'];
                 $syncedCalendar->identifier = $link['entity_id'];
                 $syncedCalendar->created = date(DATE_TIME);
                 $syncedCalendar->save();
             }
         }
     }
     return $stats;
 }
Exemplo n.º 3
0
 /**
  * Adds a entry to the feed list
  */
 function addItem($i)
 {
     switch (get_class($i)) {
         case 'cd\\NewsItem':
             $item = $i;
             break;
         case 'cd\\VideoResource':
             d($i);
             die;
             //    d($i);
             //convert into a NewsItem
             $item = new NewsItem();
             $item->title = $i->title;
             $item->desc = $i->desc;
             $item->image_url = $i->thumbnail;
             $item->image_mime = file_get_mime_by_suffix($i->thumbnail);
             $item->Url->set($i->Url->get());
             $item->Duration->set($i->Duration->get());
             $item->Timestamp->set($i->Timestamp->get());
             break;
         default:
             throw new \Exception('cant handle ' . get_class($i));
     }
     parent::addItem($item);
 }
Exemplo n.º 4
0
/**
 * {g:a} = $_GET['a']
 * {p:a} = $_POST['a']
 * {v:a} = d('var')->get('a');
 * {}
 */
function v($str)
{
    //get
    preg_match_all('/{g:(.+?)}/', $str, $elements);
    if (!empty($elements[1])) {
        foreach ($elements[1] as $v) {
            $str = str_replace('{g:' . $v . '}', $_GET[$v], $str);
        }
    }
    //post
    preg_match_all('/{p:(.+?)}/', $str, $elements);
    if (!empty($elements[1])) {
        foreach ($elements[1] as $v) {
            $str = str_replace('{p:' . $v . '}', $_POST[$v], $str);
        }
    }
    //var
    preg_match_all('/{v:(.+?)}/', $str, $elements);
    if (!empty($elements[1])) {
        foreach ($elements[1] as $v) {
            $str = str_replace('{v:' . $v . '}', d('var')->get('a'), $str);
        }
    }
    return $str;
}
Exemplo n.º 5
0
 function dump_post()
 {
     global $post;
     ob_start('kint_debug_globals');
     d($post);
     ob_end_flush();
 }
 public function __construct(Registry $Registry, array $aData)
 {
     $this->Registry = $Registry;
     $this->aData = $aData;
     d('$this->aData: ' . print_r($this->aData, 1));
     $this->User = $Registry->Viewer;
 }
Exemplo n.º 7
0
 /**
  * Same as d(), but first test the debug level.
  * @see d
  *
  * @param int $lvl Required debug level for output.
  * @param string $msg Message to output.
  * @param mixed $var Variable to be shown.
  */
 function dv($lvl, $msg, $var = NULL)
 {
     global $debug;
     if ($debug >= $lvl) {
         d($msg, $var);
     }
 }
Exemplo n.º 8
0
 public function call(Server\Request $req = null, Server\Error $err = null)
 {
     d('CALLING NEWS/SEARCH (#3)');
     $res = parent::call($req, $err);
     // $res->write('<p>URI: '.$req->uri.'</p>');
     return $res;
 }
Exemplo n.º 9
0
 /**
  * Список всех элементов
  */
 function index()
 {
     $obj_list = $this->obj_name() . "_list";
     $model_name = $this->model_name();
     d()->{$obj_list} = d()->{$model_name};
     print d()->view();
 }
Exemplo n.º 10
0
 /**
  * Make html block with data about
  * external Twitter account (avatar, username)
  *
  * @return string html block
  */
 protected function makeBlockExternal()
 {
     d('oViewer: ' . print_r($this->oViewer->getArrayCopy(), 1));
     $aVals = array('LinkedIn', $this->oViewer->getAvatarImgSrc(), $this->oViewer['fn'] . ' ' . $this->oViewer['ln']);
     $s = \tplAvatarblock::parse($aVals, false);
     return $s;
 }
Exemplo n.º 11
0
 public static function validSignature($clientId, $sig, $ts)
 {
     # is req sig still valid
     $tsClean = str_replace('V', '', str_replace('C', '', $ts));
     $currentTime = gmdate('YmdHis');
     $minTime = gmdate('YmdHis', strtotime('-1 hours'));
     if ($tsClean < $minTime) {
         throw new \Exception('--request object expired--');
     } else {
         # calc the sig from client id, signature, and timestamp
         # canonical request string
         # 	- method
         # 	- host
         # 	- uri
         # 	- access-key
         # 	- query-string
         # 	- timestamp
         $clientSecret = consumer::$clientSecret;
         $reqUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
         $reqMethod = $_SERVER['REQUEST_METHOD'];
         $host = 'vassar.api.dev';
         $canonical = "{$reqMethod}\n{$host}\n{$reqUri}\n{$clientId}\n\n{$ts}";
         $digest = hash_hmac('SHA256', $canonical, $clientSecret);
         $sigCalc = base64_encode($digest);
         d($sigCalc);
         d($sig);
         if ($sigCalc === $sig) {
             return true;
         }
     }
     return false;
 }
Exemplo n.º 12
0
 function getCheckHostResults()
 {
     $score = 0;
     foreach ($this->addedhosts as $host => $whatever) {
         $host .= '.multi.surbl.org';
         $res = SblamURI::gethostbynamel($host);
         if ($res && count($res)) {
             d($res, "found banned {$host}");
             $score += 3;
             $mask = 0;
             foreach ($res as $ip) {
                 $mask |= ip2long($ip);
             }
             $mask &= 127 - 1 - 16;
             // outblaze list has false positives, so lower score
             d($mask, "banned mask");
             while ($mask) {
                 $score++;
                 $mask >>= 1;
             }
             d("total surbl score until now is {$score}");
         } else {
             d("{$host} not listed {$res}");
         }
     }
     $finalscore = min(0.4 + $score / 25, 1.5);
     if ($score) {
         return array($finalscore, $score >= 13 ? self::CERTAINITY_HIGH : self::CERTAINITY_NORMAL, "Linked sites in SURBL (" . round($finalscore, 1) . " = {$score})");
     }
     return NULL;
 }
Exemplo n.º 13
0
 /**
  * Just dumps a simple array. Test to see if what it dumps is correct.
  *
  * @return assertion
  */
 public function testPingToLiveIp()
 {
     $randomArray = ["test" => "array", "im" => "cool", "danny" => "is awesome", "just" => "random gibberish"];
     $randomArray2 = ["more" => "stuff", "hello" => "2"];
     $randomVar = 12122;
     d($randomArray);
 }
Exemplo n.º 14
0
 public function exec()
 {
     try {
         $request = new Request();
         $url = new Url($request->server('REQUEST_URI'));
         $path = $url->path . '/' . $url->file;
         d('' . $url);
         if (!isset($this->routing[$path])) {
             throw new Exception('routing not found');
         }
         $rounting = $this->routing[$path];
         // Controllerをrequire
         require_once implode('/', [PATH_CONTROLLER, $rounting[0] . '.php']);
         $controller = $rounting[0];
         $action = $rounting[1];
         // actionを実行
         $class = new ReflectionClass($controller);
         $instance = $class->newInstance($request);
         $reflMethod = new ReflectionMethod($controller, $action . 'Action');
         $reflMethod->invoke($instance);
     } catch (Exception $e) {
         d('####### 処理されない例外 #######');
         d($e);
     }
 }
Exemplo n.º 15
0
 protected function _initialize()
 {
     $this->user_session = session('user');
     $this->assign('user_session', $this->user_session);
     $this->config = d('Config')->get_config();
     $this->config['now_city'] = 2035;
     $this->assign('config', $this->config);
     c('config', $this->config);
     $levelDb = m('User_level');
     $tmparr = $levelDb->where('22=22')->order('id ASC')->select();
     $levelarr = array();
     if ($tmparr) {
         foreach ($tmparr as $vv) {
             $levelarr[$vv['level']] = $vv;
         }
     }
     $this->user_level = $levelarr;
     unset($tmparr);
     unset($levelarr);
     $this->assign('levelarr', $this->user_level);
     $this->common_url['group_category_all'] = c('config.site_url') . '/category/all/all';
     $this->static_path = $this->config['site_url'] . '/tpl/Static/' . c('DEFAULT_THEME') . '/';
     $this->static_public = $this->config['site_url'] . '/static/';
     $this->assign('static_path', $this->static_path);
     $this->assign('static_public', $this->static_public);
     $this->assign($this->common_url);
 }
Exemplo n.º 16
0
 public function __construct(\Lampcms\Registry $Registry)
 {
     $this->Registry = $Registry;
     $this->aData = $Registry->Request->getArray();
     d('$this->aData: ' . print_r($this->aData, 1));
     $this->User = $Registry->Viewer;
 }
Exemplo n.º 17
0
 /**
  * __method_systemUser_description__
  * @return __return_systemUser_type__ __return_systemUser_description__
  * @throws Exception                  __exception_Exception_description__
  */
 public static function systemUser()
 {
     $user = self::findOne([self::tableName() . '.' . 'email' => self::SYSTEM_EMAIL], false);
     if (empty($user)) {
         $superGroup = Group::find()->disableAccessCheck()->where(['system' => 'super_administrators'])->one();
         if (!$superGroup) {
             return false;
         }
         $userClass = self::className();
         $user = new $userClass();
         $user->scenario = 'creation';
         $user->first_name = 'System';
         $user->last_name = 'User';
         $user->email = self::SYSTEM_EMAIL;
         $user->status = static::STATUS_INACTIVE;
         $user->password = Yii::$app->security->generateRandomKey();
         $user->relationModels = [['parent_object_id' => $superGroup->primaryKey]];
         if (!$user->save()) {
             \d($user->email);
             \d($user->errors);
             throw new Exception("Unable to save system user!");
         }
     }
     return $user;
 }
Exemplo n.º 18
0
 function get_compiled_response()
 {
     if (isset(d()->datapool['inputs_with_errors']) && count(d()->datapool['inputs_with_errors']) != 0 && isset($_POST['_element'])) {
         $noticed_inputs = array_values(d()->datapool['inputs_with_errors']);
         $this->response .= "\$('.error, .has-error').removeClass('error').removeClass('has-error');\n";
         if ($_POST['_action'] == htmlspecialchars($_POST['_action'])) {
             //$this->response.=  "var _tmp_form = $('input[value=".$_POST['_action']."]').parents('form');\n";
             $this->response .= "var _tmp_form = _current_form[0];\n";
         } else {
             $this->response .= "var _tmp_form = \$(\$('form')[0]);\n";
         }
         $first_element = array();
         foreach ($noticed_inputs as $key => $input) {
             if (isset($_POST['_is_simple_names']) && $_POST['_is_simple_names'] == '1') {
                 $element_name = "'*[name=\"" . $input . "\"]'";
             } else {
                 $element_name = "'*[name=\"" . $_POST['_element'] . '[' . $input . ']' . "\"]'";
             }
             $this->response .= '$(' . $element_name . ', _tmp_form).parent().parent().addClass("error").addClass("has-error");' . "\n";
             if (isset($_POST['_is_simple_names']) && $_POST['_is_simple_names'] == '1') {
                 $first_element[] = "*[name=\"" . $input . "\"]";
             } else {
                 $first_element[] = "*[name=\"" . $_POST['_element'] . '[' . $input . ']' . "\"]";
             }
         }
         if ($first_element != '') {
             $this->response .= "\$(\$('" . implode(', ', $first_element) . "',  _tmp_form)[0]).focus();" . "\n";
         }
     }
     return $this->response;
 }
 public function actionIndex()
 {
     $solr = new Solr('deal-category');
     $solr->getService()->deleteByQuery('*:*');
     $cats = KeywordCategory::model()->findAll();
     $allkeywords = '';
     foreach ($cats as $c) {
         $sql = "select term from Keyword where category = {$c->id}";
         $command = Yii::app()->db->createCommand($sql);
         $rows = $command->queryColumn();
         $doc = $solr->getDoc();
         $doc->id = trim($c->name);
         $doc->keywords = implode(" ", $rows);
         $allkeywords .= $doc->keywords . ' ';
         d($doc);
         $solr->getService()->addDocument($doc);
     }
     $doc = $solr->getDoc();
     $doc->id = "Services & Others";
     $doc->keywords = $allkeywords;
     $solr->getService()->addDocument($doc);
     $solr->getService()->commit();
     $solr->getService()->optimize();
     $this->render('index');
 }
Exemplo n.º 20
0
 function preTestPost(ISblamPost $p)
 {
     $text = preg_replace('/\\[:..:\\]\\s+/', ' ', $p->getRawContent());
     if (strlen($text) < 40) {
         $text .= $p->getAuthorURI();
     }
     if (strlen($text) < 40) {
         $text .= $p->getAuthorEmail();
     }
     if (strlen($text) < 40) {
         $text .= $p->getAuthorName();
     }
     if (strlen($text) < 20) {
         $text .= $p->getAuthorIP();
     }
     if (strlen($text) < 10) {
         $this->checksum = NULL;
         return;
     }
     $text = preg_replace(array('/[.,\\s!:;()-]+/', '/([a-f0-9]{1,3}[a-f]{1,6}[0-9]{1,6})+/', '/\\d\\d{1,8}/'), array(' ', 'H', 'D'), strtolower($text));
     d($text, 'normalized text');
     $this->length = strlen($text);
     $this->checksum = md5($text);
     if (!$this->db->exec(sprintf("/*maxtime5*/INSERT INTO dupes (checksum,count,expires,ip) VALUES(UNHEX('%s'),1,%d,%u)\n\t\t\tON DUPLICATE KEY UPDATE count = 1 + IF(expires < %d,CEIL(count/10),count), expires = GREATEST(expires + 3600*6, %d)", $this->checksum, time() + 3600 * 18, ip2long($p->getAuthorIP()), time(), time() + 3600 * 18))) {
         warn($this->db->errorInfo());
     }
 }
Exemplo n.º 21
0
/**
 * May be set as exception handler, i.e. set_exception_handler('alkemann\h2l\handleError');
 *
 * @param \Throwable $e
 */
function handleError(\Throwable $e)
{
    if ($e instanceof \alkemann\h2l\exceptions\InvalidUrl) {
        Log::info("InvalidUrl: " . $e->getMessage());
        echo (new Error(404, $e->getMessage()))->render();
        return;
    }
    if ($e instanceof \Exception) {
        Log::error(get_class($e) . ": " . $e->getMessage());
    } elseif ($e instanceof \Error) {
        Log::alert(get_class($e) . ": " . $e->getMessage());
    }
    if (DEBUG && isset($e->xdebug_message)) {
        header("Content-type: text/html");
        echo '<table>' . $e->xdebug_message . '</table><br>';
        dbp('xdebug_message');
        d($e);
    } elseif (DEBUG) {
        header("Content-type: text/html");
        echo '<h1>' . $e->getMessage() . '</h1>';
        d($e);
    } else {
        (new Error(500, $e->getMessage()))->render();
    }
}
Exemplo n.º 22
0
 public function testD()
 {
     ob_start();
     d(true);
     $res = ob_get_clean();
     $this->assertEquals("bool(true)\n", $res);
 }
Exemplo n.º 23
0
function pd($v)
{
    echo '<pre>';
    print_r($v);
    echo '</pre>';
    d();
}
Exemplo n.º 24
0
 public function authorize()
 {
     $request = \OAuth2\Request::createFromGlobals();
     $response = new \OAuth2\Response();
     $server = $this->oauth;
     // validate the authorize request
     if (!$server->validateAuthorizeRequest($request, $response)) {
         $response->send();
         d(var_dump($is_authorized));
         //die;
     }
     // display an authorization form
     if (!$this->request->isPost()) {
         exit('
     <form method="post">
       <label>Do You Authorize TestClient?</label><br />
       <input type="submit" name="authorized" value="yes">
       <input type="submit" name="authorized" value="no">
     </form>');
     }
     // print the authorization code if the user has authorized your client
     $is_authorized = $_POST['authorized'] == 'yes';
     $server->handleAuthorizeRequest($request, $response, $is_authorized);
     if ($is_authorized) {
         // this is only here so that you get to see your code in the cURL request. Otherwise, we'd redirect back to the client
         $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=') + 5, 40);
         exit("SUCCESS! Authorization Code: {$code}");
     }
     $response->send();
 }
Exemplo n.º 25
0
 /**
  * Parse title of the question by
  * tokenizing it
  * Overrides parent's parse and users mb_split
  * instead of preg_split to be UTF-8 Safe
  * because title can be a UTF-8 string
  *
  * @return array tokens;
  */
 public function parse()
 {
     if (empty($this->origString)) {
         d('string was empty, returning empty array');
         return array();
     }
     \mb_regex_encoding('UTF-8');
     $aTokens = \mb_split('([\\s,;\\"\\?]+)', $this->origString);
     $aTokens = \array_unique($aTokens);
     $aStopwords = getStopwords();
     \array_walk($aTokens, function (&$val) use($aStopwords) {
         $val = \trim($val);
         $val = strlen($val) > 1 && !in_array($val, $aStopwords) ? $val : false;
     });
     /**
      * Remove empty values
      *
      */
     $aTokens = \array_filter($aTokens);
     /**
      * Call array_values to reindex from 0
      * otherwise if filter removed some
      * elements then Mongo will not
      * treat this as normal array
      */
     return \array_values($aTokens);
 }
Exemplo n.º 26
0
 public function twig_kint_dump($var)
 {
     if (!$this->isEnabled()) {
         return '';
     }
     return @d($var);
 }
Exemplo n.º 27
0
/**
 * Debug function with die() after
 * dd($var);
 * @param $var
 */
function dd($var)
{
    $tmp_var = debug_backtrace(1);
    $caller = array_shift($tmp_var);
    d($var, $caller);
    die;
}
Exemplo n.º 28
0
function storeAlitudeToDb($altitudes, $caches, &$cachesAltitudeCount)
{
    $status = (string) $altitudes->status;
    if ($status !== 'OK') {
        print 'error occured';
        d($caches, $altitudes);
        return;
    }
    $db = \lib\Database\DataBaseSingleton::Instance();
    $i = 0;
    foreach ($altitudes->result as $key => $value) {
        $lat = (string) $value->location->lat;
        $lon = (string) $value->location->lng;
        $alt = (string) $value->elevation;
        $altInt = (int) round($alt);
        if (round($caches[$i]['latitude'], 7) == $lat && round($caches[$i]['longitude'], 7) == $lon) {
            $query2 = 'INSERT INTO caches_additions (cache_id, altitude) VALUES (:2, :1) ';
            $db->multiVariableQuery($query2, $altInt, $caches[$i]['cache_id']);
        }
        // d($altInt, $key, $value, $lat, $lon, $caches[$i]);
        $i++;
        $cachesAltitudeCount++;
    }
    return $cachesAltitudeCount;
}
Exemplo n.º 29
0
/**
 * Debug function with die() after
 * dd($var);
 */
function dd($var)
{
    $dtrace = debug_backtrace(1);
    $caller = array_shift($dtrace);
    d($var, $caller);
    die;
}
Exemplo n.º 30
0
 public function index()
 {
     return false;
     phpinfo();
     return false;
     //CModel::make('login_model');
     echo strtotime('+3 days 2 hours 14 minutes');
     //echo time();
     return false;
     echo $id = $this->input->get('id');
     d($id);
     return true;
     //$this->load->model('run_model');
     // $this->run_model->test();
     // d($this->uri->rsegment(2));
     // var_dump($diffTime);
     $retval = $this->DateDiff('d', 1409050905, 1409335310);
     $unit = array('y', 'm', 'w', 'd', 'h', 'n', 's');
     $lang = array('y' => '年', 'm' => '月', 'w' => '周', 'd' => '天', 'h' => '小时', 'n' => '分', 's' => '秒');
     foreach ($unit as $abbr) {
         $log[$abbr] = $this->DateDiff($abbr, 1409050905, 1409335310);
     }
     foreach ($log as $key => $value) {
         if ($value > 0) {
             echo $value . $lang[$key] . '前';
             break;
         }
     }
 }