示例#1
0
文件: json.php 项目: kotkotofey/eight
function to_json(array $data)
{
    $isArray = true;
    $keys = array_keys($data);
    $prevKey = -1;
    // Необходимо понять — перед нами список или ассоциативный массив.
    foreach ($keys as $key) {
        if (!is_numeric($key) || $prevKey + 1 != $key) {
            $isArray = false;
            break;
        } else {
            $prevKey++;
        }
    }
    unset($keys);
    $items = array();
    foreach ($data as $key => $value) {
        $item = !$isArray ? "\"{$key}\":" : '';
        if (is_array($value)) {
            $item .= to_json($value);
        } elseif (is_null($value)) {
            $item .= 'null';
        } elseif (is_bool($value)) {
            $item .= $value ? 'true' : 'false';
        } elseif (is_string($value)) {
            $item .= '"' . preg_replace('%([\\x00-\\x1f\\x22\\x5c])%e', 'sprintf("\\\\u%04X", ord("$1"))', $value) . '"';
        } elseif (is_numeric($value)) {
            $item .= $value;
        } else {
            throw new Exception('Wrong argument.');
        }
        $items[] = $item;
    }
    return ($isArray ? '[' : '{') . implode(',', $items) . ($isArray ? ']' : '}');
}
示例#2
0
/**
 * Checks required GET parameters and dies if they are not valid or found
 *
 * @param $params
 *   The $_GET parameters in an array like: 'cid' => 'numeric', 'cid' => 'string'
 * @return
 *   FALSE if params invalid or missing
 *   
 */
function check_required_get_params($params)
{
    $errors = array();
    foreach ($params as $key => $type) {
        switch ($type) {
            case 'numeric':
                if (!isset($_GET[$key]) || !is_numeric($_GET[$key])) {
                    $errors[] = "Missing or invalid required param: {$key} ({$type})";
                }
                break;
            case 'string':
                if (!isset($_GET[$key])) {
                    $errors[] = "Missing or invalid required param: {$key} ({$type})";
                }
                break;
            default:
                if (!isset($_GET[$key])) {
                    $errors[] = "Missing or invalid required param: {$key} ({$type})";
                }
        }
    }
    if (isset($errors[0])) {
        die(to_json(array('success' => FALSE, 'code' => 15, 'errors' => $errors)));
    }
}
function format_inline($inline, $num, $id, $preview_html = null)
{
    if (!$inline->inline_images) {
        return "";
    }
    $url = $inline->inline_images->first->preview_url();
    if (!$preview_html) {
        $preview_html = '<img src="' . $url . '">';
    }
    $id_text = "inline-{$id}-{$num}";
    $block = '
    <div class="inline-image" id="' . $id_text . '">
      <div class="inline-thumb" style="display: inline;">
      ' . $preview_html . '
      </div>
      <div class="expanded-image" style="display: none;">
        <div class="expanded-image-ui"></div>
        <span class="main-inline-image"></span>
      </div>
    </div>
  ';
    $inline_id = "inline-{$id}-{$num}";
    $script = 'InlineImage.register("' . $inline_id . '", ' . to_json($inline) . ');';
    return array($block, $script, $inline_id);
}
示例#4
0
function avatar_init()
{
    $posts = Comment::avatar_post_reg(true);
    if (!$posts) {
        return;
    }
    $ret = '';
    foreach ($posts as $post) {
        $ret .= "Post.register(" . to_json($post) . ")\n";
    }
    $ret .= 'Post.init_blacklisted';
    return $ret;
}
示例#5
0
 protected function autoContentType($data)
 {
     if (gettype($data) == "string") {
         $content_type = 'text/html';
         $body = $data;
     } else {
         $content_type = 'application/json';
         $body = to_json($data);
     }
     // only set content-type if it wans't set manually.
     if ($this->app->response->headers->get('Content-type') == "text/html") {
         $this->app->response->headers->set('Content-type', $content_type);
     }
     $this->app->response->setBody($body);
 }
function respond_to_list($inst_var)
{
    // $inst_var = instance_variable_get("@#{inst_var_name}")
    // global $$inst_var_name;
    // $inst_var = &$$inst_var_name;
    switch (Request::$format) {
        case 'json':
            if (method_exists($inst_var, 'to_json')) {
                render('json', $inst_var->to_json());
            } else {
                render('json', to_json($inst_var));
            }
            break;
        case 'xml':
            break;
    }
}
示例#7
0
 static function render($type, $value = null, $params = array())
 {
     if ($type === false) {
         self::$params['nothing'] = true;
         return;
     }
     if (is_int(strpos($type, '#'))) {
         /**
          * We're rendering a controller/action file.
          * In this case, $value holds the params, and we only change
          * the 'render' value and return. We can't call the
          * render file within this or any function because of variables scope.
          * 
          * This is expected to occur in a controller, therefore in the controller one must
          * also return; after calling this function, so further code won't be executed.
          */
         list($ctrl, $act) = explode('#', parse_url_token($type));
         self::parse_parameters($value);
         self::$render = VIEWPATH . "{$ctrl}/{$act}.php";
         return;
     }
     # Running after-filters.
     ActionController::run_after_filters();
     self::parse_parameters($params);
     if ($type == 'json') {
         header('Content-Type: application/json; charset=utf-8');
         if (is_array($value)) {
             $value = to_json($value);
         }
         echo $value;
         exit;
     } elseif ($type == 'xml') {
         header('Content-type: application/rss+xml; charset=UTF-8');
         if (is_array($value) || is_object($value)) {
             $root = isset($params['root']) ? $params['root'] : 'response';
             $value = to_xml($value, $root);
         }
         echo $value;
         exit;
     } elseif ($type == 'inline') {
         self::$params['render_type'] = 'inline';
         self::$params['render_value'] = $value;
         include SYSROOT . 'action_view/render_markup_default.php';
     }
 }
 public static function serialize($protocolMessage)
 {
     if (!is_a($protocolMessage, 'ProtocolMessage')) {
         throw new ProtocolMessageSerializationException('Provided object is not a ProtocolMessage.');
     }
     if (!$protocolMessage->validate()) {
         throw new ProtocolMessageSerializationException('Provided object fails validation.');
     }
     /*$array = array();
     
         foreach ($protocolMessage as $key => $value) {
           $array[$key] = $value;
         }*/
     $serial = to_json($protocolMessage);
     if ($serial === null) {
         throw new ProtocolMessageSerializationException('Unable to serialize message (unknown encoding error): ' . json_last_error_msg());
     }
     return $serial;
 }
示例#9
0
?>
  </ul>
  </div>
</div>
<script type="text/javascript">
  function remove_post_confirm(post_id, pool_id) {
    if (!$("del-mode") || !$("del-mode").checked) {
      return true
    }

    Pool.remove_post(post_id, pool_id)
    return false
  }

  Post.register_resp(<?php 
echo to_json(Post::batch_api_data($posts));
?>
);
</script>
<?php 
echo render_partial('post/hover');
?>

<div id="paginator">
  <?php 
paginator();
?>

  <div style="display: none;" id="info">When delete mode is enabled, clicking on a thumbnail will remove the post from this pool.</div>
</div>
<?php 
示例#10
0
function zopim_customize_widget()
{
    global $current_user;
    $ul = $current_user->data->first_name;
    $useremail = $current_user->data->user_email;
    $greetings = json_to_array(get_option('zopimGreetings'));
    $message = "";
    if (count($_POST) > 0) {
        update_option('zopimLang', $_POST["zopimLang"]);
        update_option('zopimPosition', $_POST["zopimPosition"]);
        update_option("zopimBubbleEnable", $_POST["zopimBubbleEnable"]);
        update_option('zopimColor', $_POST["zopimColor"]);
        update_option('zopimTheme', $_POST["zopimTheme"]);
        update_option('zopimBubbleTitle', stripslashes($_POST["zopimBubbleTitle"]));
        update_option('zopimBubbleText', stripslashes($_POST["zopimBubbleText"]));
        update_checkbox("zopimGetVisitorInfo");
        update_checkbox("zopimHideOnOffline");
        update_checkbox("zopimUseGreetings");
        update_checkbox("zopimUseBubble");
        if (isset($_POST['zopimUseGreetings']) && $_POST['zopimUseGreetings'] != "") {
            $greetings->online->window = stripslashes($_POST["zopimOnlineLong"]);
            $greetings->online->bar = stripslashes($_POST["zopimOnlineShort"]);
            $greetings->away->window = stripslashes($_POST["zopimAwayLong"]);
            $greetings->away->bar = stripslashes($_POST["zopimAwayShort"]);
            $greetings->offline->window = stripslashes($_POST["zopimOfflineLong"]);
            $greetings->offline->bar = stripslashes($_POST["zopimOfflineShort"]);
            update_option('zopimGreetings', to_json($greetings));
        }
        $message = "<b>Changes saved!</b><br>";
    }
    zopimme();
    $accountDetails = getAccountDetails(get_option('zopimSalt'));
    if (get_option('zopimCode') == "zopim") {
        $message = '<div class="metabox-holder">
	<div class="postbox">
		<h3 class="hndle"><span>Customizing in Demo Mode</span></h3>
		<div style="padding:10px;line-height:17px;">
			Currently customizing in demo mode. Messages in this widget will go to Zopim staff. The chat widget will not appear on your site until you <a href="admin.php?page=zopim_account_config">activate / link up an account</a>. <br>
		</div>
	</div>
		</div>';
        $accountDetails->widget_customization_enabled = 1;
        $accountDetails->color_customization_enabled = 1;
    } else {
        if (isset($accountDetails->error)) {
            $message = '<div class="metabox-holder">
								<div class="postbox">
								<h3 class="hndle"><span>Account no longer linked!</span></h3>
								<div style="padding:10px;line-height:17px;">
									We could not connect to your Zopim account. As a result, this customization page is running in demo mode.<br> Please <a href="admin.php?page=zopim_account_config">check your password in account setup</a> and try again.
								</div>
								</div>
								</div>';
        } else {
            $message .= "Click 'Save Changes' when you're done. Happy customizing!";
        }
    }
    // unset($accountDetails->widget_customization_enabled);
    // unset($accountDetails->color_customization_enabled);
    ?>

	<script type="text/javascript">

	function updateWidget() {
		var lang = document.getElementById('zopimLang').options[ document.getElementById('zopimLang').options.selectedIndex ].value;
		$zopim.livechat.setLanguage(lang);

		if (document.getElementById("zopimGetVisitorInfo").checked) {
			$zopim.livechat.setName('<?php 
    echo $ul;
    ?>
');
			$zopim.livechat.setEmail('<?php 
    echo $useremail;
    ?>
');
		}
		else {
			$zopim.livechat.setName('Visitor');
			$zopim.livechat.setEmail('');
		}

		document.getElementById("zopimHideOnOffline").checked? $zopim.livechat.button.setHideWhenOffline(true): $zopim.livechat.button.setHideWhenOffline(false);

		$zopim.livechat.window.setColor(document.getElementById("zopimColor").value);
		$zopim.livechat.window.setTheme(document.getElementById("zopimTheme").value);

		if (document.getElementById("zopimUseBubble").checked) {
			$zopim.livechat.bubble.setTitle(document.getElementById("zopimBubbleTitle").value);
			$zopim.livechat.bubble.setText(document.getElementById("zopimBubbleText").value);
		}
		else {
			$zopim.livechat.bubble.setTitle('Questions?');
			$zopim.livechat.bubble.setText('Click here to chat with us!');
		}

		$zopim.livechat.setGreetings({
			'online':  [document.getElementById("zopimOnlineShort").value, document.getElementById("zopimOnlineLong").value],
			'offline': [document.getElementById("zopimOfflineShort").value, document.getElementById("zopimOfflineLong").value],
			'away':    [document.getElementById("zopimAwayShort").value, document.getElementById("zopimAwayLong").value]
		});
	}

	function updatePosition() {
		var position = document.getElementById('zopimPosition').options[ document.getElementById('zopimPosition').options.selectedIndex ].value;
		$zopim.livechat.button.setPosition(position);
	}

	function updateBubbleStatus() {
		var value = document.getElementById("zopimBubbleEnable").value;
		switch (value) {
			case 'default':
				$zopim.livechat.bubble.reset();
				break;
			case 'show':
				$zopim.livechat.bubble.show();
				break;
			case 'hide':
				$zopim.livechat.bubble.hide();
				break;
		}
	}

	function greetingsChanged() {
		var inputs     = [ 'zopimOnlineShort', 'zopimAwayShort', 'zopimOfflineShort',
											 'zopimOnlineLong' , 'zopimAwayLong', 'zopimOfflineLong' ];
		var isDisabled = false;

		document.getElementById('zopimUseGreetings').checked? (isDisabled = false): (isDisabled = true);

		for (var i=0; i<inputs.length; i++) {
			document.getElementById(inputs[i]).disabled = isDisabled;
		}

		updateWidget();
	}

	function bubbleChanged() {
		var inputs     = [ 'zopimBubbleTitle', 'zopimBubbleText' ];
		var isDisabled = false;

		document.getElementById('zopimUseBubble').checked? (isDisabled = false): (isDisabled = true);

		for (var i = 0; i < inputs.length; i++) {
			document.getElementById(inputs[i]).disabled = isDisabled;
		}

		updateWidget();
	}

	var timer;
	function updateSoon() {
		clearTimeout(timer);
		timer = setTimeout("updateWidget()", 300);
	}

	</script>

<style type="text/css">
.smallExplanation {
background:#FAFAFA;
color:#667788;
font-size:8pt;
line-height:13px;
margin:4px 0 0 0;
padding:8px;
display: inline-block;
}
.inputtextshort {
width:200px;
}
.inputtext {
width:450px;
}
.secthead {
border-bottom:1px solid #EEEEEE;
color:#8899AA;
font-size:13px;
line-height:21px;
}
.sethead {
	width:200px;
}
.swatch {
	float: left;
	width: 15px
}
.swatch:hover {
	background-image:url(http://www.zopim.com/static/images/colorselectbg.gif);
	cursor:pointer;
}
.sorry {
	color:#c33;
}
</style>

<div class="wrap">
<div id="icon-themes" class="icon32"><br/></div><h2>Customize your widget</h2>

<?php 
    echo $message;
    ?>
<form method="post" action="admin.php?page=zopim_customize_widget">
<div class="metabox-holder">
	<div class="postbox">
		<h3 class="hndle"><span>General Settings</span></h3>
		<div style="padding:10px;">
		<table class="form-table">
			<tr valign="top">
				<th scope="row" class="sethead">Language</th>
				<td>
					<select name="zopimLang" id="zopimLang" onchange="updateWidget()">
<?php 
    $languages = get_languages();
    echo generate_options($languages, get_option('zopimLang'));
    ?>
				</select>
				</td>
				</tr>
				<tr valign="top" style="display:none;">
				<th scope="row">Use Logged in Username / Email</th>
				<td><input onchange="updateWidget()" type="checkbox" id="zopimGetVisitorInfo" name="zopimGetVisitorInfo" value="zopimGetVisitorInfo" <?php 
    if (get_option('zopimGetVisitorInfo') != "disabled") {
        echo "checked='checked'";
    }
    ?>
 /></td>
				</tr>
				<tr valign="top">
				<th scope="row" class="sethead">Position</th>
				<td>

				<select name="zopimPosition" id="zopimPosition" onchange="updatePosition()">
<?php 
    $positions = array("br" => "Bottom Right", "bl" => "Bottom Left");
    echo generate_options($positions, get_option('zopimPosition'));
    ?>
				</select>
				</td>
				</tr>

				<tr valign="top">
				<th scope="row">Hide chat bar when offline<br>
				<!-- <div class="smallExplanation">Hide the chat bar when no agents are available to answer questions. This prevents visitors from sending you offline messages. </div>  -->
				</th>
					<td>
						<input onchange="updateWidget()" type="checkbox" id="zopimHideOnOffline" name="zopimHideOnOffline" value="zopimHideOnOffline" <?php 
    if (get_option('zopimHideOnOffline') && get_option('zopimHideOnOffline') != "disabled") {
        echo "checked='checked'";
    }
    ?>
 /> Prevents visitors from sending you offline messages
						<a href="#" onclick="$zopim.livechat.button.show();return false">(Show preview chat bar)</a>
					</td>
				</tr>
		</table>
		</div>
	</div>
</div>
<div class="metabox-holder">
	<div class="postbox">
		<h3 class="hndle"><span>Color & Theme Settings</span></h3>
		<div style="padding:10px;">
		Theme settings show up instantly on the preview widget. Try it out!<br/>
		<table class="form-table" style="width: 700px">
				<tr valign="top">
				<td colspan="2">
				<input type="hidden" id="zopimColor" name="zopimColor" value="<?php 
    echo get_option('zopimColor');
    ?>
">
<?php 
    if ($accountDetails->color_customization_enabled == 1) {
        echo "<div style='display:inline-block;border:11px solid #888;background:#888;color:#fee;'>";
        $colors = curl_get_url(ZOPIM_COLORS_LIST);
        $colors = explode("\n", $colors);
        $i = 0;
        foreach ($colors as $color) {
            echo "<div class='swatch' style='background-color: {$color};' onclick=\"document.getElementById('zopimColor').value='{$color}'; updateWidget();\">&nbsp</div>";
            if (++$i % 40 == 0) {
                echo "<br>";
            }
        }
        echo "<br><a href=# style='color:#ff8' onclick=\"document.getElementById('zopimColor').value=''; updateWidget();\">Restore default color</a></div>";
    } else {
        echo "<div class='sorry'>Sorry, your plan does not allow for color customization. Please upgrade to enjoy choice of color!</div>";
    }
    ?>
				</td>
				</tr>
				<tr valign="top">
				<th scope="row" class="sethead">Select A Theme</th>
				<td style="width: 400px"><div align="left">
<?php 
    if ($accountDetails->widget_customization_enabled == 1) {
        echo '<select name="zopimTheme" id="zopimTheme" onchange="updateWidget()">';
        $themes = curl_get_url(ZOPIM_THEMES_LIST);
        $themes = valuekeys(explode("\n", $themes));
        ksort($themes);
        echo generate_options($themes, get_option('zopimTheme'));
        echo "</select> <a href='#' onclick='\$zopim.livechat.window.toggle();return false;'>Open the chat panel</a> to see changes";
    } else {
        echo "<div class='sorry'>Sorry, your plan does not allow for theme customization. Please upgrade to enjoy choice of themes!</div>";
        echo '<input type=hidden value="" name="zopimTheme" id="zopimTheme">';
    }
    ?>
				</td>
				</tr>
		</table>
		</div>
	</div>
</div>

<?php 
    get_option('zopimUseBubble') && get_option('zopimUseBubble') != "disabled" ? $useBubble = true : ($useBubble = false);
    ?>
<div class="metabox-holder">
	<div class="postbox">
		<h3 class="hndle"><span>Help Bubble Settings</span></h3>
		<div style="padding:10px;">
		<table class="form-table">
			<tr valign="top">
				<th scope="row">Display Help Bubble<br></th>
				<td><select onchange="updateBubbleStatus()" type="checkbox" id="zopimBubbleEnable" name="zopimBubbleEnable"> <?php 
    $bubble_modes = array("default" => "Let user decide", "show" => "Always show", "hide" => "Always hide");
    echo generate_options($bubble_modes, get_option('zopimBubbleEnable'));
    ?>
	</select>
			</tr>
			<tr>
				<td colspan="2"><div class="secthead">Help Bubble Text</div></td>
			</tr>
			<tr>
				<td colspan="2"><input type="checkbox" id="zopimUseBubble" onchange="bubbleChanged()" value="zopimUseBubble" name="zopimUseBubble" <?php 
    if ($useBubble) {
        echo "checked='checked'";
    }
    ?>
/> Enable help bubble text settings (override dashboard settings) - save settings to view changes.</td>
			</tr>
			<tr valign="top">
				<th scope="row" class="sethead">Help Bubble Title</th>
				<td><input class="inputtextshort" name="zopimBubbleTitle" id="zopimBubbleTitle" onKeyup="updateSoon()" value="<?php 
    echo get_option('zopimBubbleTitle');
    ?>
"  <?php 
    if (!$useBubble) {
        echo "disabled='disabled'";
    }
    ?>
><!-- <a href="#" onclick="updateBubbleStatus();">Refresh</a></td> -->
			</tr>
			<tr valign="top">
				<th scope="row" class="sethead">Help Bubble Message</th>
				<td><input class="inputtext" name="zopimBubbleText" id="zopimBubbleText" onKeyup="updateSoon()" value="<?php 
    echo get_option('zopimBubbleText');
    ?>
"  <?php 
    if (!$useBubble) {
        echo "disabled='disabled'";
    }
    ?>
></td>
			</tr>
		</table>
		</div>
	</div>
</div>

<?php 
    get_option('zopimUseGreetings') && get_option('zopimUseGreetings') != "disabled" ? $useGreetings = true : ($useGreetings = false);
    ?>
<div class="metabox-holder">
	<div class="postbox">
		<h3 class="hndle"><span>Greeting Message Settings</span></h3>
		<div style="padding:10px;">
		<table class="form-table">
			<tr>
				<td colspan="2"><input type="checkbox" id="zopimUseGreetings" onchange="greetingsChanged()" value="zopimUseGreetings" name="zopimUseGreetings" <?php 
    if ($useGreetings) {
        echo "checked='checked'";
    }
    ?>
/>	Enable greeting message settings (override dashboard settings) </td>
			</tr>
			<tr>
				<td colspan="2"><div class="secthead">Message Shown on Chat Bar (max 26 characters)</div></td>
			</tr>
			<tr valign="top">
				<th scope="row" class="sethead">Online</th>
				<td><input class="inputtextshort" name="zopimOnlineShort" id="zopimOnlineShort" onKeyup="updateSoon()" value="<?php 
    echo $greetings->online->bar;
    ?>
" <?php 
    if (!$useGreetings) {
        echo "disabled='disabled'";
    }
    ?>
 maxlength="26"></td>
			</tr>
			<tr valign="top">
				<th scope="row" class="sethead">Away</th>
				<td><input class="inputtextshort" name="zopimAwayShort" id="zopimAwayShort" onKeyup="updateSoon()"  value="<?php 
    echo $greetings->away->bar;
    ?>
"  <?php 
    if (!$useGreetings) {
        echo "disabled='disabled'";
    }
    ?>
  maxlength="26"></td>
			</tr>
			<tr valign="top">
				<th scope="row" class="sethead">Offline</th>
				<td><input class="inputtextshort" name="zopimOfflineShort" id="zopimOfflineShort" onKeyup="updateSoon()" value="<?php 
    echo $greetings->offline->bar;
    ?>
" <?php 
    if (!$useGreetings) {
        echo "disabled='disabled'";
    }
    ?>
  maxlength="26"></td>
			</tr>
			<tr>
				<td colspan="2"><div class="secthead">Message Shown on Chat Panel (max 140 characters)</div></td>
			</tr>
			<tr valign="top">
				<th scope="row" class="sethead">Online</th>
				<td><textarea class="inputtext" name="zopimOnlineLong" id="zopimOnlineLong" onKeyup="updateSoon()"  <?php 
    if (!$useGreetings) {
        echo "disabled='disabled'";
    }
    ?>
 ><?php 
    echo $greetings->online->window;
    ?>
</textarea></td>
			</tr>
			<tr valign="top">
				<th scope="row" class="sethead">Away</th>
				<td><textarea class="inputtext" name="zopimAwayLong" id="zopimAwayLong" onKeyup="updateSoon()" <?php 
    if (!$useGreetings) {
        echo "disabled='disabled'";
    }
    ?>
 ><?php 
    echo $greetings->away->window;
    ?>
</textarea></td>
			</tr>
			<tr valign="top">
				<th scope="row" class="sethead">Offline</th>
				<td><textarea class="inputtext" name="zopimOfflineLong" id="zopimOfflineLong" onKeyup="updateSoon()"  <?php 
    if (!$useGreetings) {
        echo "disabled='disabled'";
    }
    ?>
 ><?php 
    echo $greetings->offline->window;
    ?>
</textarea></td>
			</tr>
		</table>
		</div>
	</div>
</div>

<p class="submit">
	<input type="submit" class="button-primary" value="<?php 
    _e('Save Changes');
    ?>
" />
</p>

</form>
</div>

<?php 
}
示例#11
0
<?php

/**
 * @file
 * Get tweet details based on a twitter id
 */
session_start();
require_once $_SERVER['DOCUMENT_ROOT'] . '/config/main.conf.php';
require $_SERVER['DOCUMENT_ROOT'] . '/lib/helpers.php';
require $_SERVER['DOCUMENT_ROOT'] . '/lib/twitoauth/twitteroauth.php';
/* If access tokens are not available redirect to connect page. */
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
    header('Location: /twitoauth/clearsessions.php');
    exit;
}
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$connection->decode_json = TRUE;
$result = $connection->post("friendships/create/{$_GET['screen_name']}");
$success = isset($result->id) ? TRUE : FALSE;
$message = isset($result->errors) ? $result->errors : NULL;
$return_array = array('success' => $success, 'message' => $message);
$json_string = to_json($return_array);
error_log("favorites JSON String: " . $json_string);
print $json_string;
示例#12
0
		INNER JOIN status_channel ON status.id = status_channel.status_id 
		WHERE (status_channel.channel_id = ? ' . $chanzero . ') AND id < ?
		ORDER BY status_channel.status_id DESC LIMIT ?');
    $stmt->bind_param('idi', $_GET['cid'], $_GET['maxid'], $limit);
} else {
    $stmt = $mysqli->prepare('SELECT id, screen_name, profile_image_url, created_at, source, text 
		FROM status 
		INNER JOIN status_channel ON status.id = status_channel.status_id 
		WHERE status_channel.channel_id = ? ' . $chanzero . '
		ORDER BY status_channel.status_id DESC LIMIT ?');
    $stmt->bind_param('ii', $_GET['cid'], $limit);
}
$stmt->execute();
$stmt->bind_result($id, $screen_name, $profile_image_url, $created_at, $source, $text);
$next_page_maxid = NULL;
while ($stmt->fetch()) {
    $created_at_timestamp = strtotime($created_at);
    $tweets[] = array('id' => $id, 'screen_name' => $screen_name, 'profile_image_url' => $profile_image_url, 'created_at' => nice_time($created_at_timestamp), 'created_at_long' => date('m-d-y h:i A', $created_at_timestamp), 'source' => $source, 'text' => $text);
    $next_page_maxid = $id;
}
$stmt->close();
$return_array = array('tweets' => $tweets, 'next_page_maxid' => $next_page_maxid);
print to_json($return_array);
if ($do_cache) {
    $contents = ob_get_contents();
    ob_end_clean();
    $handle = fopen($cachefile, 'w');
    fwrite($handle, $contents);
    fclose($handle);
    include $cachefile;
}
示例#13
0
 function to_json($params = array())
 {
     return to_json($this->api_attributes(), $params);
 }
示例#14
0
<div id="paginator">
  <?php 
paginator();
?>
</div>

<?php 
do_content_for("post_cookie_javascripts");
?>
<script type="text/javascript">
  var thumb = $("hover-thumb");
  <?php 
foreach ($samples as $k => $post) {
    ?>
    Post.register(<?php 
    echo to_json($post);
    ?>
);
    var hover_row = $("p<?php 
    echo $pools->{$k}->id;
    ?>
");
    var container = hover_row.up("TABLE");
    Post.init_hover_thumb(hover_row, <?php 
    echo $post->id;
    ?>
, thumb, container);
  <?php 
}
?>
  Post.init_blacklisted({replace: true});
<?php

require_once "getquery.php";
$species = get("species");
$query = "\nSELECT\n    a.id as \"id\",\n    a.name as \"name\",\n    a.description as \"description\"\nFROM\n    ability as a";
if ($species) {
    $query .= "\n    ,\n    species as s\nWHERE\n    s.id={$species}\n    AND a.id <>0\n    AND (\n        s.ability1=a.id OR\n        s.ability2=a.id OR\n        s.ability3=a.id\n    )\n;";
}
$result = run_query($query);
echo to_json($result);
if ($file['error'] == UPLOAD_ERR_OK) {
    // and move the file to it's destination
    if (!@move_uploaded_file($file['tmp_name'], "{$uploadPath}/{$file['name']}")) {
        $error = t("Can't move uploaded file into the {$uploadPath} directory");
    }
} else {
    switch ($file['error']) {
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            $error = t('File is too big.');
            break;
        case UPLOAD_ERR_PARTIAL:
            $error = t('File was only partially uploaded.');
            break;
        case UPLOAD_ERR_NO_FILE:
            $error = t('No file was uploaded.');
            break;
        case UPLOAD_ERR_NO_TMP_DIR:
            $error = t('Missing a temporary upload folder.');
            break;
        case UPLOAD_ERR_CANT_WRITE:
            $error = t('Failed to write file to disk.');
            break;
        case UPLOAD_ERR_EXTENSION:
            $error = t('File upload stopped by extension.');
            break;
    }
}
// print results for AJAX handler
echo to_json(array('error' => $error, 'path' => $uploadPath, 'file' => $file['name'], 'tmpfile' => $file['tmp_name'], 'size' => $file['size']));
        return json_encode($var);
    } else {
        $encoder = new Services_JSON();
        return $encoder->encode($var);
    }
}
$task = JRequest::getCmd('task', '');
switch ($task) {
    case 'getdirectory':
        // Return the output directory in JSON format
        $registry =& JoomlapackModelRegistry::getInstance();
        $outdir = $registry->get('OutputDirectory');
        // # Fix 2.4: Drop the output buffer
        if (function_exists('ob_clean')) {
            @ob_clean();
        }
        echo to_json($outdir);
        break;
    default:
        // Return the CUBE array in JSON format
        $cube =& JoomlapackCUBE::getInstance();
        $array = $cube->getCUBEArray();
        // # Fix 2.4: Drop the output buffer
        if (function_exists('ob_clean')) {
            @ob_clean();
        }
        echo to_json($array);
        break;
}
# Fix 2.4: Die the script in order to avoid misbehaving modules from ruining the output
die;
示例#18
0
<?php

require_once "getquery.php";
$s = get("species");
$ruleset = get("ruleset");
$query = "\nSELECT\n    m.*\nFROM\n    move as m";
$where = array();
$i = 0;
if ($ruleset !== False) {
    $query .= " LEFT OUTER JOIN banmove as b ON\n        m.id = b.move AND b.ruleset={$ruleset}";
    $where[$i++] = "(b.move IS NULL)";
}
if ($s) {
    $subq = json_decode(to_json(run_query("\n        SELECT * FROM moveset WHERE id={$s}\n    ")));
    $moves = "(" . implode(", ", explode(" ", $subq[0]->moves)) . ")";
    $egg_moves = "(" . implode(", ", explode(" ", $subq[0]->egg_moves)) . ")";
    $where[$i++] = "(m.id IN {$moves}" . ($subq[0]->egg_moves ? " OR m.id IN {$egg_moves})" : ")");
}
if ($i == 0) {
    $where = "";
} else {
    $where = "WHERE " . implode(" AND ", $where);
}
echo to_json(run_query("{$query} {$where}"));
示例#19
0
         header("Bad URI", false, 400);
         print "Bad URI";
         return;
     }
     $a_roll = load_cfg();
     #print_r($a_roll);
     try {
         $id = get_rol_index_by_number($a_roll, $number);
     } catch (RollNotFoundException $ex) {
         header("Not found", false, 404);
         print "Not found";
         return;
     }
     $rol = $a_roll[$id];
     header("Content-Type: application/json");
     $data = to_json($rol);
     print $data;
     break;
 case DELETE:
     $id = -1;
     if (preg_match('/^\\/roll\\/(\\w+)\\/(\\d+)\\/?$/', $_SERVER['PATH_INFO'], $matches)) {
         $cpzone = strtolower($matches[1]);
         $number = $matches[2];
     } else {
         header("Bad URI", false, 400);
         print "Bad URI";
         return;
     }
     $a_roll = load_cfg();
     #END load_cfg
     try {
示例#20
0
                $output = array('success' => TRUE, 'code' => 1, 'message' => 'created user and sent activation mail');
            }
        } else {
            if ($user['status'] == 1) {
                $output = array('success' => FALSE, 'code' => 2, 'message' => 'pending confirmation');
            } else {
                if ($user['status'] == 2) {
                    $output = array('success' => TRUE, 'code' => 3, 'message' => 'user is already unlocked');
                }
            }
        }
    }
} else {
    $output = array('success' => FALSE, 'code' => 6, 'message' => 'email field required');
}
print to_json($output);
/**
 * Adds a user to the db and sends the activation email
 *
 * @param $mysqli
 *   A mysqli connection
 * @param $email
 *   Email address of user
 * @return
 *   TRUE if user is successfully added user and sent mail
 */
function create_user_send_activation($mysqli, $email)
{
    $unique = uniqid();
    if ($stmt = $mysqli->prepare('INSERT INTO user (email, status, uniqid) VALUES (?, 1, ?)')) {
        $stmt->bind_param('ss', $email, $unique);
示例#21
0
文件: Logger.php 项目: CFLOVEYR/hook
 public static function notice($message)
 {
     return Router::getInstance()->log->notice("[NOTICE] " . to_json($message));
 }
示例#22
0
    if ($_REQUEST["parse"]) {
        $parse = $_REQUEST['parse'];
        switch (true) {
            case $parse == "fitbitauth":
                $fitbit = new Fitbit();
                if ($fitbit->fetchAuthToken()) {
                    // we have the auth token.  user is already linked
                    $userMsg = "Your Fitbit and C3HealthLink accounts have already been linked.";
                } elseif ($fitbit->fetchReqToken()) {
                    if ($fitbit->getAuthToken($oauthToken) === true) {
                        $userMsg = "Congratulations, you have successfully linked your Fitbit and C3HealthLink accounts.";
                    } else {
                        $resp["url"] = $fitbit->getReqTokenURL();
                    }
                } else {
                    $resp["url"] = $fitbit->getReqTokenURL();
                    $userMsg = '';
                    //No message needed - it redirects to Fitbit, then back to here as a callback.
                }
                $resp["content"] = $userMsg;
                echo to_json($resp);
                break;
        }
        //es
    }
    //end parse check
}
class DevicesView
{
}
//ec
<?php 
require_once "getquery.php";
$query = "SELECT * FROM ruleset as r GROUP BY r.id ORDER BY r.id ASC";
echo $json = to_json(run_query($query));
示例#24
0
 public function index($name)
 {
     $query = Model\App::collection($name)->filter(Input::get('q'));
     // Select fieds
     if ($fields = Input::get('select')) {
         $query = $query->select($fields);
     }
     // Distinct keyword
     if ($distinct = Input::get('distinct')) {
         $query = $query->distinct();
     }
     // Apply ordering
     if ($s = Input::get('s', array(array('_id', 'asc')))) {
         foreach ($s as $ordering) {
             $query->orderBy(reset($ordering), end($ordering));
         }
     }
     // Apply group
     if ($group = Input::get('g')) {
         foreach ($group as $field) {
             $query = $query->groupBy($field);
         }
     }
     $offset = Input::get('offset');
     $limit = Input::get('limit');
     //
     // Append total rows if performing a pagination
     //
     // FIXME: We should use more elegant solution here with headers:
     // 'Range', 'Accept-Ranges' and 'Content-Range'
     //
     if ($limit !== NULL && $offset !== NULL) {
         Response::header('Access-Control-Expose-Headers', 'X-Total-Count');
         Response::header('X-Total-Count', $query->count());
     }
     // limit / offset
     if ($limit) {
         $query = $query->take($limit);
     }
     if ($offset) {
         $query = $query->skip($offset);
     }
     // remember / caching
     if ($remember = Input::get('remember')) {
         throw new NotImplementedException('remember/cache not implemented');
         // $query = $query->remember($remember);
     }
     // with - eager load relationships
     if ($with = Input::get('with')) {
         $query = call_user_func_array(array($query, 'with'), $with);
     }
     if ($aggr = Input::get('aggr')) {
         // Aggregate 'max'/'min'/'avg'/'sum' methods
         if (isset($aggr['field'])) {
             $aggregate = $query->{$aggr['method']}($aggr['field']);
         } else {
             // Aggregate 'count'
             $aggregate = $query->{$aggr['method']}();
         }
         Response::header('Content-type', 'application/json');
         Response::setBody(to_json($aggregate));
         return true;
     } elseif ($paginate = Input::get('p')) {
         throw new NotImplementedException('Pagination not implemented. use limit/offset.');
     } elseif (Input::get('f')) {
         // First
         return $query->first();
     } else {
         return $query->get();
     }
 }
示例#25
0
 /**
  * json
  *
  * @param mixed $data
  */
 protected function json($data)
 {
     $response = Router::getInstance()->response;
     $response->headers->set('Content-type', 'application/json');
     $response->setBody(to_json($data));
 }
示例#26
0
<?php

echo to_json($custom_fields);
示例#27
0
<?php

require_once "getquery.php";
$handle = @fopen("regulations.txt", "r");
$query = "INSERT INTO banspecies (ruleset, species) VALUES ";
if ($handle) {
    while (($buffer = fgets($handle)) !== false) {
        $buffer = substr($buffer, 0, strlen($buffer) - 2);
        $ids = json_decode(to_json(run_query("\n            SELECT id FROM species WHERE name=\"{$buffer}\"\n        ")));
        $query .= "(1, " . $ids[0]->id . "),";
    }
}
echo $query;
run_query(substr($query, 0, strlen($query) - 1));
die("Done!");
示例#28
0
function json_error_handler($errno, $errstr, $errfile, $errline)
{
    if (!(error_reporting() & $errno)) {
        return;
    }
    header('Content-type: application/json');
    header('HTTP/1.1 500 Internal Server Error');
    // # TODO: hardcoded system's folder name.
    $errfile = addslashes(str_replace(array('\\', ROOT), array('/', ''), $errfile));
    // $errfile = addslashes(preg_replace('~^(.*)\/myimouto~', '', str_replace('\\', '/', $errfile)));
    switch ($errno) {
        case E_USER_ERROR:
            $e = "Fatal: [{$errno}] {$errstr}<br />({$errfile}:{$errline})";
            break;
        case E_USER_WARNING:
            $e = "Warning: [{$errno}] {$errstr}<br />({$errfile}:{$errline})";
            break;
        case E_USER_NOTICE:
            $e = "Notice: [{$errno}] {$errstr}<br />({$errfile}:{$errline})";
            break;
        default:
            $e = "[{$errno}] {$errstr}<br />({$errfile}:{$errline})";
            break;
    }
    exit(to_json(array('reason' => $e)));
}
示例#29
0
function zopim_account_config()
{
    global $usernameToCodeURL, $languagesURL, $current_user;
    ?>
<div class="wrap">
<?php 
    if (isset($_GET["action"]) && $_GET["action"] == "deactivate") {
        update_option('zopimSalt', "");
        update_option('zopimCode', "zopim");
    }
    $message = "";
    $authenticated = "";
    if (isset($_POST["action"]) && $_POST["action"] == "login") {
        if ($_POST["zopimUsername"] != "" && $_POST["zopimPassword"] != "") {
            $logindata = array("email" => $_POST["zopimUsername"], "password" => $_POST["zopimPassword"]);
            $loginresult = json_to_array(zopim_post_request(ZOPIM_LOGIN_URL, $logindata));
            if (isset($loginresult->error)) {
                $error["login"] = "******";
                $gotologin = 1;
                update_option('zopimSalt', "wronglogin");
            } else {
                if (isset($loginresult->salt)) {
                    update_option('zopimUsername', $_POST["zopimUsername"]);
                    update_option('zopimSalt', $loginresult->salt);
                    $account = getAccountDetails(get_option('zopimSalt'));
                    $editor = setEditor(get_option('zopimSalt'));
                    if (isset($account)) {
                        update_option('zopimCode', $account->account_key);
                        if (get_option('zopimGreetings') == "") {
                            $jsongreetings = to_json($account->settings->greetings);
                            update_option('zopimGreetings', $jsongreetings);
                        }
                    }
                } else {
                    update_option('zopimSalt', "");
                    $error["login"] = "******";
                }
            }
        } else {
            update_option('zopimSalt', "wronglogin");
            $gotologin = 1;
            $error["login"] = "******";
        }
    } else {
        if (isset($_POST["action"]) && $_POST["action"] == "signup") {
            $createdata = array("email" => $_POST["zopimnewemail"], "first_name" => $_POST["zopimfirstname"], "last_name" => $_POST["zopimlastname"], "display_name" => $_POST["zopimfirstname"] . " " . $_POST["zopimlastname"], "eref" => $_POST["zopimeref"], "source" => "wordpress", "recaptcha_challenge_field" => $_POST["recaptcha_challenge_field"], "recaptcha_response_field" => $_POST["recaptcha_response_field"]);
            $signupresult = json_to_array(zopim_post_request(ZOPIM_SIGNUP_URL, $createdata));
            if (isset($signupresult->error)) {
                $message = "<div style='color:#c33;'>Error during activation: <b>" . $signupresult->error . "</b>. Please try again.</div>";
            } else {
                if (isset($signupresult->account_key)) {
                    $message = "<b>Thank you for signing up. Please check your mail for your password to complete the process. </b>";
                    $gotologin = 1;
                } else {
                    $message = "<b>Could not activate account. The wordpress installation was unable to contact Zopim servers. Please check with your server administrator to ensure that <a href='http://www.php.net/manual/en/book.curl.php'>PHP Curl</a> is installed and permissions are set correctly.</b>";
                }
            }
        }
    }
    if (get_option('zopimCode') != "" && get_option('zopimCode') != "zopim") {
        $accountDetails = getAccountDetails(get_option('zopimSalt'));
        if (!isset($accountDetails) || isset($accountDetails->error)) {
            $gotologin = 1;
            $error["auth"] = '
	 <div class="metabox-holder">
	<div class="postbox">
		<h3 class="hndle"><span>Account no longer linked!</span></h3>
		<div style="padding:10px;line-height:17px;">
		We could not verify your Zopim account. Please check your password and try again.
		</div>
	</div>
	 </div>';
        } else {
            $authenticated = "ok";
        }
    }
    if ($authenticated == "ok") {
        if ($accountDetails->package_id == "trial") {
            $accountDetails->package_id = "Free Lite Package + 14 Days Full-features";
        } else {
            $accountDetails->package_id .= " Package";
        }
        ?>
<div id="icon-options-general" class="icon32"><br/></div><h2>Set up your Zopim Account</h2>
<br/>
<div style="background:#FFFEEB;padding:25px;border:1px solid #eee;">
<span style="float:right;"><a href="admin.php?page=zopim_account_config&action=deactivate">Deactivate</a></span>
Currently Activated Account &rarr; <b><?php 
        echo get_option('zopimUsername');
        ?>
</b> <div style="display:inline-block;margin-left:5px;background:#444;color:#fff;font-size:10px;text-transform:uppercase;padding:3px 8px;-moz-border-radius:5px;-webkit-border-radius:5px;"><?php 
        echo ucwords($accountDetails->package_id);
        ?>
</div>
<!--<br><p><br>You can <a href="admin.php?page=zopim_customize_widget">customize</a> the chat widget, or <a href="admin.php?page=zopim_dashboard">launch the dashboard</a> for advanced features.-->
<br><br>To start using Zopim chat, launch our dashboard for access to all features, including widget customization!
<br><br><a href="<?php 
        echo ZOPIM_DASHBOARD_LINK . "&username="******" style="text-decoration:none;" target="_blank" data-popup="true"><div class="zopim_btn_orange">Launch Dashboard</div></a>&nbsp;&nbsp;(This will open up a new browser tab)


<form method="post" action="admin.php?page=zopim_account_config">
	<?php 
        if (isset($_POST['widget-options'])) {
            $opts = $_POST['widget-options'];
            update_option('zopimWidgetOptions', $opts);
            echo '<i>Widget options updated.<br/></i>';
        }
        ?>
	<p>
	Optional code for customization with Zopim API:
	<br/>
	<textarea name="widget-options" style="width:680px; height: 200px;"><?php 
        echo esc_textarea(zopim_get_widget_options());
        ?>
</textarea>
	<br/>
	<input class="button-primary" type="submit" value="Update widget options" />
	</p>
</form>

</div>
<?php 
    } else {
        ?>
<div id="icon-options-general" class="icon32"><br/></div><h2>Set up your Zopim Account</h2>
<?php 
        if (isset($error["auth"])) {
            echo $error["auth"];
        } else {
            if ($message == "") {
                ?>
Congratulations on successfully installing the Zopim WordPress plugin!<br>
<br>
<?php 
            } else {
                echo $message;
            }
        }
        ?>
<div id="existingform">
	<div class="metabox-holder">
		<div class="postbox">
			<h3 class="hndle"><span>Link up with your Zopim account</span></h3>
			<div style="padding:10px;">
<?php 
        if (isset($error["login"])) {
            echo '<span class="error">' . $error["login"] . '</span>';
        }
        ?>
<form method="post" action="admin.php?page=zopim_account_config">
	<input type="hidden" name="action" value="login">
	<table class="form-table">

			<tr valign="top">
			<th scope="row">Zopim Username (E-mail)</th>
			<td><input type="text" name="zopimUsername" value="<?php 
        echo get_option('zopimUsername');
        ?>
" /></td>
			</tr>

			<tr valign="top">
			<th scope="row">Zopim Password</th>
			<td><input type="password" name="zopimPassword" value="" /></td>
			</tr>

			<!--<tr valign="center">
			<th scope="row">Use SSL</th>
			<td><input type="checkbox" name="zopimUseSSL" value="zopimUseSSL" <?php 
        if (get_option('zopimUseSSL') == "zopimUseSSL") {
            echo "checked='checked'";
        }
        ?>
 /> uncheck this if you are unable to login</td>
			</tr>-->
	 </table>
		<br/>
		The Zopim chat widget will display on your blog after your account is linked up.
		<br/>
		<p class="submit">
		<input id="linkup" type="submit" onclick="animateButton()" class="button-primary" value="<?php 
        _e('Link Up');
        ?>
" />
		&nbsp;Don't have a Zopim account? <a href="<?php 
        echo ZOPIM_SIGNUP_REDIRECT_URL;
        ?>
" target="_blank" data-popup="true">Sign up now</a>.
		</p>

</form>

			</div>
		</div>
	</div>
</div>

</div>


<?php 
    }
}
示例#30
0
文件: base.php 项目: brego/prank
 /**
  * Returns a JSON representation of this models data
  *
  * @return string
  */
 public function to_json()
 {
     use_helper('json.php');
     return to_json($this->data);
 }