code
stringlengths 12
2.05k
| label_name
stringclasses 5
values | label
int64 0
4
|
---|---|---|
$link = str_replace(URL_FULL, '', makeLink(array('section' => $section->id)));
| Base | 1 |
function db_start()
{
global $DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName, $DatabasePort, $DatabaseType;
switch ($DatabaseType) {
case 'mysqli':
$connection = new mysqli($DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName, $DatabasePort);
break;
}
// Error code for both.
if ($connection === false) {
switch ($DatabaseType) {
case 'mysqli':
$errormessage = mysqli_error($connection);
break;
}
db_show_error("", "" . _couldNotConnectToDatabase . ": $DatabaseServer", $errormessage);
}
return $connection;
} | Base | 1 |
public function approve_submit() {
if (empty($this->params['id'])) {
flash('error', gt('No ID supplied for comment to approve'));
expHistory::back();
}
/* The global constants can be overriden by passing appropriate params */
//sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];
// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];
// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];
// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];
$comment = new expComment($this->params['id']);
$comment->body = $this->params['body'];
$comment->approved = $this->params['approved'];
$comment->save();
expHistory::back();
} | Base | 1 |
$query->whereExists(function ($permissionQuery) use (&$tableDetails, $action) {
/** @var Builder $permissionQuery */
$permissionQuery->select(['role_id'])->from('joint_permissions')
->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
->where('action', '=', $action)
->whereIn('role_id', $this->getCurrentUserRoles())
->where(function (QueryBuilder $query) {
$this->addJointHasPermissionCheck($query, $this->currentUser()->id);
});
});
}); | Class | 2 |
public function checkout($name)
{
$this->run('checkout', $name);
return $this;
} | Class | 2 |
$emails[$u->email] = trim(user::getUserAttribution($u->id));
}
| Base | 1 |
public function updateTab($id, $array)
{
if (!$id || $id == '') {
$this->setAPIResponse('error', 'id was not set', 422);
return null;
}
if (!$array) {
$this->setAPIResponse('error', 'no data was sent', 422);
return null;
}
$tabInfo = $this->getTabById($id);
if ($tabInfo) {
$array = $this->checkKeys($tabInfo, $array);
} else {
$this->setAPIResponse('error', 'No tab info found', 404);
return false;
}
if (array_key_exists('name', $array)) {
$array['name'] = htmlspecialchars($array['name']);
if ($this->isTabNameTaken($array['name'], $id)) {
$this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);
return false;
}
}
if (array_key_exists('default', $array)) {
if ($array['default']) {
$this->clearTabDefault();
}
}
$response = [
array(
'function' => 'query',
'query' => array(
'UPDATE tabs SET',
$array,
'WHERE id = ?',
$id
)
),
];
$this->setAPIResponse(null, 'Tab info updated');
$this->setLoggerChannel('Tab Management');
$this->logger->debug('Edited Tab Info for [' . $tabInfo['name'] . ']');
return $this->processQueries($response);
} | Base | 1 |
public static function activate($mod){
$json = Options::v('modules');
$mods = json_decode($json, true);
//print_r($mods);
if (!is_array($mods) || $mods == "") {
$mods = array();
}
if (!in_array($mod, $mods)) {
# code...
$mods = array_merge($mods, array($mod));
}
$mods = json_encode($mods);
$mods = Options::update('modules', $mods);
if($mods){
new Options();
return true;
}else{
return false;
}
}
| Base | 1 |
function getTextColumns($table) {
$sql = "SHOW COLUMNS FROM " . $this->prefix.$table . " WHERE type = 'text' OR type like 'varchar%'";
$res = @mysqli_query($this->connection, $sql);
if ($res == null)
return array();
$records = array();
while($row = mysqli_fetch_object($res)) {
$records[] = $row->Field;
}
return $records;
} | Base | 1 |
foreach ($cf_d as $cfd_i => $cfd_d) {
if ($cfd_i == 'TYPE') {
$fc = substr($cfd_d, 0, 1);
$lc = substr($cfd_d, 1);
$cfd_d = strtoupper($fc) . $lc;
$get_schools_cf[$cf_i][$cfd_i] = $cfd_d;
unset($fc);
unset($lc);
}
if ($cfd_i == 'SELECT_OPTIONS' && $cf_d['TYPE'] != 'text') {
for ($i = 0; $i < strlen($cfd_d); $i++) {
$char = substr($cfd_d, $i, 1);
if (ord($char) == '13')
$char = '<br/>';
$new_char[] = $char;
}
$cfd_d = implode('', $new_char);
$get_schools_cf[$cf_i][$cfd_i] = $cfd_d;
unset($char);
unset($new_char);
}
if ($cfd_i == 'SYSTEM_FIELD' || $cfd_i == 'REQUIRED') {
if ($cfd_d == 'N')
$get_schools_cf[$cf_i][$cfd_i] = 'No';
if ($cfd_d == 'Y')
$get_schools_cf[$cf_i][$cfd_i] = 'Yes';
}
} | Base | 1 |
private function get_submit_action() {
$action = null;
if ( isset( $_POST['geo_mashup_add_location'] ) or isset( $_POST['geo_mashup_update_location'] ) ) {
// Clients without javascript may need server side geocoding
if ( ! empty( $_POST['geo_mashup_search'] ) and isset( $_POST['geo_mashup_no_js'] ) and 'true' == $_POST['geo_mashup_no_js'] ) {
$action = 'geocode';
} else {
$action = 'save';
}
} else if ( isset( $_POST['geo_mashup_changed'] ) and 'true' == $_POST['geo_mashup_changed'] and ! empty( $_POST['geo_mashup_location'] ) ) {
// The geo mashup submit button wasn't used, but a change was made and the post saved
$action = 'save';
} else if ( isset( $_POST['geo_mashup_delete_location'] ) ) {
$action = 'delete';
} else if ( ! empty( $_POST['geo_mashup_location_id'] ) and empty( $_POST['geo_mashup_location'] ) ) {
// There was a location, but it was cleared before this save
$action = 'delete';
}
return $action;
}
| Class | 2 |
public function confirm()
{
$project = $this->getProject();
$swimlane = $this->getSwimlane();
$this->response->html($this->helper->layout->project('swimlane/remove', array(
'project' => $project,
'swimlane' => $swimlane,
)));
} | Base | 1 |
function manage_upcharge() {
$this->loc->src = "@globalstoresettings";
$config = new expConfig($this->loc);
$this->config = $config->config;
$gc = new geoCountry();
$countries = $gc->find('all');
$gr = new geoRegion();
$regions = $gr->find('all',null,'rank asc,name asc');
assign_to_template(array(
'countries'=>$countries,
'regions'=>$regions,
'upcharge'=>!empty($this->config['upcharge'])?$this->config['upcharge']:''
));
} | Base | 1 |
public static function endReset( &$parser, $text ) {
if ( !self::$createdLinks['resetdone'] ) {
self::$createdLinks['resetdone'] = true;
foreach ( $parser->getOutput()->mCategories as $key => $val ) {
if ( array_key_exists( $key, self::$fixedCategories ) ) {
self::$fixedCategories[$key] = $val;
}
}
// $text .= self::dumpParsedRefs($parser,"before final reset");
if ( self::$createdLinks['resetLinks'] ) {
$parser->getOutput()->mLinks = [];
}
if ( self::$createdLinks['resetCategories'] ) {
$parser->getOutput()->mCategories = self::$fixedCategories;
}
if ( self::$createdLinks['resetTemplates'] ) {
$parser->getOutput()->mTemplates = [];
}
if ( self::$createdLinks['resetImages'] ) {
$parser->getOutput()->mImages = [];
}
// $text .= self::dumpParsedRefs( $parser, 'after final reset' );
self::$fixedCategories = [];
}
return true;
} | Class | 2 |
protected function make($path, $name, $mime) {
$sql = 'INSERT INTO %s (`parent_id`, `name`, `size`, `mtime`, `mime`, `content`, `read`, `write`) VALUES ("%s", "%s", 0, %d, "%s", "", "%d", "%d")';
$sql = sprintf($sql, $this->tbf, $path, $this->db->real_escape_string($name), time(), $mime, $this->defaults['read'], $this->defaults['write']);
// echo $sql;
return $this->query($sql) && $this->db->affected_rows > 0;
} | Base | 1 |
public function display_sdm_upload_meta_box($post) { // File Upload metabox
$old_upload = get_post_meta($post->ID, 'sdm_upload', true);
$old_value = isset($old_upload) ? $old_upload : '';
_e('Manually enter a valid URL of the file in the text box below, or click "Select File" button to upload (or choose) the downloadable file.', 'simple-download-monitor');
echo '<br /><br />';
echo '<div class="sdm-download-edit-file-url-section">';
echo '<input id="sdm_upload" type="text" size="100" name="sdm_upload" value="' . $old_value . '" placeholder="http://..." />';
echo '</div>';
echo '<br />';
echo '<input id="upload_image_button" type="button" class="button-primary" value="' . __('Select File', 'simple-download-monitor') . '" />';
echo '<br /><br />';
_e('Steps to upload a file or choose one from your media library:', 'simple-download-monitor');
echo '<ol>';
echo '<li>Hit the "Select File" button.</li>';
echo '<li>Upload a new file or choose an existing one from your media library.</li>';
echo '<li>Click the "Insert" button, this will populate the uploaded file\'s URL in the above text field.</li>';
echo '</ol>';
wp_nonce_field('sdm_upload_box_nonce', 'sdm_upload_box_nonce_check');
} | Base | 1 |
foreach ($value as $i => $j) {
$column_check = explode('_', $i);
if ($column_check[0] == 'CUSTOM') {
$check_validity = DBGet(DBQuery('SELECT COUNT(*) as REC_EX FROM school_custom_fields WHERE ID=' . $column_check[1] . ' AND (SCHOOL_ID=' . $get_school_info[$key]['ID'].' OR SCHOOL_ID=0)'));
if ($check_validity[1]['REC_EX'] == 0)
$j = 'NOT_AVAILABLE_FOR';
}
$get_school_info[$key][$i] = trim($j);
} | Base | 1 |
static function description() {
return "Manage events and schedules, and optionally publish them.";
}
| Class | 2 |
echo '</SCHOOL_' . htmlentities($i) . '>';
$i++;
}
echo '</SCHOOL_ACCESS>';
// }
echo '</STAFF_' . htmlentities($j) . '>';
$j++;
} | Base | 1 |
public function search(){
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria = new CDbCriteria;
$username = Yii::app()->user->name;
$criteria->addCondition("uploadedBy='$username' OR private=0 OR private=null");
$criteria->addCondition("associationType != 'theme'");
return $this->searchBase($criteria);
} | Base | 1 |
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = false)
{
$this->catch = $catch;
$this->backendRequest = $request;
return parent::handle($request, $type, $catch);
} | Class | 2 |
public function update(CurrencyFormRequest $request, TransactionCurrency $currency)
{
/** @var User $user */
$user = auth()->user();
$data = $request->getCurrencyData();
if (false === $data['enabled'] && $this->repository->currencyInUse($currency)) {
$data['enabled'] = true;
}
if (!$this->userRepository->hasRole($user, 'owner')) {
$request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));
Log::channel('audit')->info('Tried to update (POST) currency without admin rights.', $data);
return redirect(route('currencies.index'));
}
$currency = $this->repository->update($currency, $data);
Log::channel('audit')->info('Updated (POST) currency.', $data);
$request->session()->flash('success', (string) trans('firefly.updated_currency', ['name' => $currency->name]));
app('preferences')->mark();
if (1 === (int) $request->get('return_to_edit')) {
$request->session()->put('currencies.edit.fromUpdate', true);
return redirect(route('currencies.edit', [$currency->id]));
}
return redirect($this->getPreviousUri('currencies.edit.uri'));
} | Compound | 4 |
public function remove()
{
$this->checkCSRFParam();
$project = $this->getProject();
$action = $this->actionModel->getById($this->request->getIntegerParam('action_id'));
if (! empty($action) && $this->actionModel->remove($action['id'])) {
$this->flash->success(t('Action removed successfully.'));
} else {
$this->flash->failure(t('Unable to remove this action.'));
}
$this->response->redirect($this->helper->url->to('ActionController', 'index', array('project_id' => $project['id'])));
} | Base | 1 |
$chrootPath = realpath($chrootPath);
if ($chrootPath !== false && strpos($realfile, $chrootPath) === 0) {
$chrootValid = true;
break;
}
}
if ($chrootValid !== true) {
throw new Exception("Permission denied on $file. The file could not be found under the paths specified by Options::chroot.");
}
$ext = strtolower(pathinfo($realfile, PATHINFO_EXTENSION));
if (!in_array($ext, $this->allowedLocalFileExtensions)) {
throw new Exception("Permission denied on $file. This file extension is forbidden");
}
if (!$realfile) {
throw new Exception("File '$file' not found.");
}
$uri = $realfile;
}
[$contents, $http_response_header] = Helpers::getFileContent($uri, $this->options->getHttpContext());
if ($contents === null) {
throw new Exception("File '$file' not found.");
}
// See http://the-stickman.com/web-development/php/getting-http-response-headers-when-using-file_get_contents/
if (isset($http_response_header)) {
foreach ($http_response_header as $_header) {
if (preg_match("@Content-Type:\s*[\w/]+;\s*?charset=([^\s]+)@i", $_header, $matches)) {
$encoding = strtoupper($matches[1]);
break;
}
}
}
$this->restorePhpConfig();
$this->loadHtml($contents, $encoding);
} | Base | 1 |
private function _titlegt( $option ) {
$where = '(';
if ( substr( $option, 0, 2 ) == '=_' ) {
if ( $this->parameters->getParameter( 'openreferences' ) ) {
$where .= 'pl_title >= ' . $this->DB->addQuotes( substr( $sTitleGE, 2 ) );
} else {
$where .= $this->tableNames['page'] . '.page_title >= ' . $this->DB->addQuotes( substr( $option, 2 ) );
}
} else {
if ( $this->parameters->getParameter( 'openreferences' ) ) {
$where .= 'pl_title > ' . $this->DB->addQuotes( $option );
} else {
$where .= $this->tableNames['page'] . '.page_title > ' . $this->DB->addQuotes( $option );
}
}
$where .= ')';
$this->addWhere( $where );
} | Class | 2 |
public function fixsessions() {
global $db;
// $test = $db->sql('CHECK TABLE '.$db->prefix.'sessionticket');
$fix = $db->sql('REPAIR TABLE '.$db->prefix.'sessionticket');
flash('message', gt('Sessions Table was Repaired'));
expHistory::back();
} | Base | 1 |
public function matchesPath($requestPath)
{
$cookiePath = $this->getPath();
// Match on exact matches or when path is the default empty "/"
if ($cookiePath == '/' || $cookiePath == $requestPath) {
return true;
}
// Ensure that the cookie-path is a prefix of the request path.
if (0 !== strpos($requestPath, $cookiePath)) {
return false;
}
// Match if the last character of the cookie-path is "/"
if (substr($cookiePath, -1, 1) == '/') {
return true;
}
// Match if the first character not included in cookie path is "/"
return substr($requestPath, strlen($cookiePath), 1) == '/';
} | Base | 1 |
public static function insert ($vars) {
if(is_array($vars)){
$set = "";
$k = "";
foreach ($vars['key'] as $key => $val) {
$set .= "'$val',";
$k .= "`$key`,";
}
$set = substr($set, 0,-1);
$k = substr($k, 0,-1);
$sql = sprintf("INSERT INTO `%s` (%s) VALUES (%s) ", $vars['table'], $k, $set) ;
}else{
$sql = $vars;
}
if(DB_DRIVER == 'mysql') {
mysql_query('SET CHARACTER SET utf8');
$q = mysql_query($sql) or die(mysql_error());
self::$last_id = mysql_insert_id();
}elseif(DB_DRIVER == 'mysqli'){
try {
if(!self::query($sql)){
printf("<div class=\"alert alert-danger\">Errormessage: %s</div>\n", self::$mysqli->error);
}else{
self::$last_id = self::$mysqli->insert_id;
}
} catch (exception $e) {
echo $e->getMessage();
}
}
return true;
} | Compound | 4 |
protected function deleteFileInStorage(Attachment $attachment)
{
$storage = $this->getStorage();
$dirPath = dirname($attachment->path);
$storage->delete($attachment->path);
if (count($storage->allFiles($dirPath)) === 0) {
$storage->deleteDirectory($dirPath);
}
} | Base | 1 |
} elseif (!is_numeric($item) && ($item != '')) {
return false;
}
}
} else {
return false;
}
} else { | Base | 1 |
public function printerFriendlyLink($link_text="Printer Friendly", $class=null, $width=800, $height=600, $view='', $title_text = "Printer Friendly") {
$url = '';
if (PRINTER_FRIENDLY != 1 && EXPORT_AS_PDF != 1) {
$class = !empty($class) ? $class : 'printer-friendly-link';
$url = '<a class="'.$class.'" href="javascript:void(0)" onclick="window.open(\'';
if (!empty($_REQUEST['view']) && !empty($view) && $_REQUEST['view'] != $view) {
$_REQUEST['view'] = $view;
}
if ($this->url_style == 'sef') {
$url .= $this->convertToOldSchoolUrl();
if (empty($_REQUEST['view']) && !empty($view)) $url .= '&view='.$view;
if ($this->url_type=='base') $url .= '/index.php?section='.SITE_DEFAULT_SECTION;
} else {
$url .= $this->current_url;
}
$url .= '&printerfriendly=1\' , \'mywindow\',\'menubar=1,resizable=1,scrollbars=1,width='.$width.',height='.$height.'\');"';
$url .= ' title="'.$title_text.'"';
$url .= '> '.$link_text.'</a>';
$url = str_replace('&ajax_action=1','',$url);
}
return $url;
} | Base | 1 |
$text .= varset($val['helpText']) ? "<div class='field-help'>".$val['helpText']."</div>" : "";
$text .= "</td>\n</tr>\n";
}
$text .="<tr>
<td>".EPL_ADLAN_59."</td>
<td>{$del_text}
<div class='field-help'>".EPL_ADLAN_60."</div>
</td>
</tr>
</table>
<div class='buttons-bar center'>";
$text .= $frm->admin_button('uninstall_confirm',EPL_ADLAN_3,'submit');
$text .= $frm->admin_button('uninstall_cancel',EPL_ADLAN_62,'cancel');
/*
$text .= "<input class='btn' type='submit' name='uninstall_confirm' value=\"".EPL_ADLAN_3."\" />
<input class='btn' type='submit' name='uninstall_cancel' value='".EPL_ADLAN_62."' onclick=\"location.href='".e_SELF."'; return false;\"/>";
*/
// $frm->admin_button($name, $value, $action = 'submit', $label = '', $options = array());
$text .= "</div>
</fieldset>
</form>
";
return $text;
e107::getRender()->tablerender(EPL_ADLAN_63.SEP.$tp->toHtml($plug_vars['@attributes']['name'], "", "defs,emotes_off, no_make_clickable"),$mes->render(). $text);
} | Compound | 4 |
$extraFields[] = ['field' => $rule->field, 'id' => $field_option['id']]; | Base | 1 |
public function withStatus($code, $reasonPhrase = '')
{
$new = clone $this;
$new->statusCode = (int) $code;
if (!$reasonPhrase && isset(self::$phrases[$new->statusCode])) {
$reasonPhrase = self::$phrases[$new->statusCode];
}
$new->reasonPhrase = $reasonPhrase;
return $new;
} | Base | 1 |
private function getDefaultConf(EasyHandle $easy)
{
$conf = [
'_headers' => $easy->request->getHeaders(),
CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(),
CURLOPT_URL => (string) $easy->request->getUri(),
CURLOPT_RETURNTRANSFER => false,
CURLOPT_HEADER => false,
CURLOPT_CONNECTTIMEOUT => 150,
];
if (defined('CURLOPT_PROTOCOLS')) {
$conf[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;
}
$version = $easy->request->getProtocolVersion();
if ($version == 1.1) {
$conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1;
} elseif ($version == 2.0) {
$conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2_0;
} else {
$conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
}
return $conf;
} | Base | 1 |
public function Connect($host, $port = 0, $tval = 30) {
// set the error val to null so there is no confusion
$this->error = null;
// make sure we are __not__ connected
if($this->connected()) {
// already connected, generate error
$this->error = array("error" => "Already connected to a server");
return false;
}
if(empty($port)) {
$port = $this->SMTP_PORT;
}
// connect to the smtp server
$this->smtp_conn = @fsockopen($host, // the host of the server
$port, // the port to use
$errno, // error number if any
$errstr, // error message if any
$tval); // give up after ? secs
// verify we connected properly
if(empty($this->smtp_conn)) {
$this->error = array("error" => "Failed to connect to server",
"errno" => $errno,
"errstr" => $errstr);
if($this->do_debug >= 1) {
$this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '<br />');
}
return false;
}
// SMTP server can take longer to respond, give longer timeout for first read
// Windows does not have support for this timeout function
if(substr(PHP_OS, 0, 3) != "WIN") {
$max = ini_get('max_execution_time');
if ($max != 0 && $tval > $max) { // don't bother if unlimited
@set_time_limit($tval);
}
stream_set_timeout($this->smtp_conn, $tval, 0);
}
// get any announcement
$announce = $this->get_lines();
if($this->do_debug >= 2) {
$this->edebug("SMTP -> FROM SERVER:" . $announce . $this->CRLF . '<br />');
}
return true;
} | Class | 2 |
$modelName = ucfirst ($module->name);
if (class_exists ($modelName)) {
// prefix widget class name with custom module model name and a delimiter
$cache[$widgetType][$modelName.'::TemplatesGridViewProfileWidget'] =
Yii::t(
'app', '{modelName} Summary', array ('{modelName}' => $modelName));
}
}
}
}
return $cache[$widgetType];
} | Class | 2 |
public static function referenceFixtures() {
return array(
'campaign' => array ('Campaign', '.CampaignMailingBehaviorTest'),
'lists' => 'X2List',
'credentials' => 'Credentials',
'users' => 'User',
'profile' => array('Profile','.marketing')
);
} | Base | 1 |
$body = str_replace(array("\n"), "<br />", $body);
} else {
// It's going elsewhere (doesn't like quoted-printable)
$body = str_replace(array("\n"), " -- ", $body);
}
$title = $items[$i]->title;
$msg .= "BEGIN:VEVENT\n";
$msg .= $dtstart . $dtend;
$msg .= "UID:" . $items[$i]->date_id . "\n";
$msg .= "DTSTAMP:" . date("Ymd\THis", time()) . "Z\n";
if ($title) {
$msg .= "SUMMARY:$title\n";
}
if ($body) {
$msg .= "DESCRIPTION;ENCODING=QUOTED-PRINTABLE:" . $body . "\n";
}
// if($link_url) { $msg .= "URL: $link_url\n";}
if (!empty($this->config['usecategories'])) {
if (!empty($items[$i]->expCat[0]->title)) {
$msg .= "CATEGORIES:".$items[$i]->expCat[0]->title."\n";
} else {
$msg .= "CATEGORIES:".$this->config['uncat']."\n";
}
}
$msg .= "END:VEVENT\n";
}
| Base | 1 |
$db->insertObject($obj, 'expeAlerts_subscribers');
}
$count = count($this->params['ealerts']);
if ($count > 0) {
flash('message', gt("Your subscriptions have been updated. You are now subscriber to")." ".$count.' '.gt('E-Alerts.'));
} else {
flash('error', gt("You have been unsubscribed from all E-Alerts."));
}
expHistory::back();
} | Base | 1 |
public function elements_count()
{
global $DB;
global $webuser;
$permission = (!empty($_SESSION['APP_USER#'.APP_UNIQUE])? 1 : 0);
// public access / webuser based / webuser groups based
$access = 2;
if(!empty($current['webuser']))
{
$access = 1;
if(!empty($webuser->groups))
{
$access_groups = array();
foreach($webuser->groups as $wg)
{
if(empty($wg))
continue;
$access_groups[] = 'groups LIKE "%g'.$wg.'%"';
}
if(!empty($access_groups))
$access_extra = ' OR (access = 3 AND ('.implode(' OR ', $access_groups).'))';
}
}
$out = $DB->query_single(
'COUNT(id)',
'nv_items',
' category = '.protect($this->id).' AND
website = '.protect($this->website).' AND
permission <= '.$permission.' AND
(date_published = 0 OR date_published < '.core_time().') AND
(date_unpublish = 0 OR date_unpublish > '.core_time().') AND
(access = 0 OR access = '.$access.$access_extra.')
');
return $out;
}
| Base | 1 |
private function edebug($str) {
if ($this->Debugoutput == "error_log") {
error_log($str);
} else {
echo $str;
}
} | Base | 1 |
return $fa->nameGlyph($icons, 'icon-');
}
} else {
return array();
}
}
| Base | 1 |
public function backup($type='json')
{
global $DB;
global $website;
$out = array();
$DB->query('SELECT * FROM nv_webdictionary WHERE website = '.protect($website->id), 'object');
if($type='json')
$out = json_encode($DB->result());
return $out;
}
| Base | 1 |
public function __construct(
GlyphFinder $glyph_finder,
ProjectXMLMerger $project_xml_merger,
ConsistencyChecker $consistency_checker,
TemplateDao $template_dao,
ProjectManager $project_manager,
EventDispatcherInterface $event_dispatcher,
) {
$this->template_dao = $template_dao;
$this->templates = [
AgileALMTemplate::NAME => new AgileALMTemplate($glyph_finder, $project_xml_merger, $consistency_checker),
ScrumTemplate::NAME => new ScrumTemplate($glyph_finder, $project_xml_merger, $consistency_checker),
KanbanTemplate::NAME => new KanbanTemplate($glyph_finder, $project_xml_merger, $consistency_checker),
IssuesTemplate::NAME => new IssuesTemplate($glyph_finder, $consistency_checker, $event_dispatcher),
EmptyTemplate::NAME => new EmptyTemplate($glyph_finder),
];
$this->project_manager = $project_manager;
$this->glyph_finder = $glyph_finder;
$this->external_templates = self::getExternalTemplatesByName($event_dispatcher);
} | Class | 2 |
public function testAddAndRemoveQueryValues()
{
$uri = new Uri('http://foo.com/bar');
$uri = Uri::withQueryValue($uri, 'a', 'b');
$uri = Uri::withQueryValue($uri, 'c', 'd');
$uri = Uri::withQueryValue($uri, 'e', null);
$this->assertEquals('a=b&c=d&e', $uri->getQuery());
$uri = Uri::withoutQueryValue($uri, 'c');
$uri = Uri::withoutQueryValue($uri, 'e');
$this->assertEquals('a=b', $uri->getQuery());
$uri = Uri::withoutQueryValue($uri, 'a');
$uri = Uri::withoutQueryValue($uri, 'a');
$this->assertEquals('', $uri->getQuery());
} | Base | 1 |
function manage_vendors () {
expHistory::set('viewable', $this->params);
$vendor = new vendor();
$vendors = $vendor->find('all');
assign_to_template(array(
'vendors'=>$vendors
));
} | Base | 1 |
public function Reset() {
$this->error = null; // so no confusion is caused
if(!$this->connected()) {
$this->error = array(
"error" => "Called Reset() without being connected");
return false;
}
fputs($this->smtp_conn,"RSET" . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($this->do_debug >= 2) {
$this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />');
}
if($code != 250) {
$this->error =
array("error" => "RSET failed",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
$this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
}
return false;
}
return true;
} | Base | 1 |
function build_daterange_sql($timestamp, $endtimestamp=null, $field='date', $multiday=false) {
if (empty($endtimestamp)) {
$date_sql = "((".$field." >= " . expDateTime::startOfDayTimestamp($timestamp) . " AND ".$field." <= " . expDateTime::endOfDayTimestamp($timestamp) . ")";
} else {
$date_sql = "((".$field." >= " . expDateTime::startOfDayTimestamp($timestamp) . " AND ".$field." <= " . expDateTime::endOfDayTimestamp($endtimestamp) . ")";
}
if ($multiday)
$date_sql .= " OR (" . expDateTime::startOfDayTimestamp($timestamp) . " BETWEEN ".$field." AND dateFinished)";
$date_sql .= ")";
return $date_sql;
}
| Base | 1 |
foreach ($events as $event) {
$extevents[$date][] = $event;
}
| Base | 1 |
private function section($nodes, $id, $filters, $start, $end, $otag, $ctag, $level)
{
$source = var_export(substr($this->source, $start, $end - $start), true);
$callable = $this->getCallable();
if ($otag !== '{{' || $ctag !== '}}') {
$delimTag = var_export(sprintf('{{= %s %s =}}', $otag, $ctag), true);
$helper = sprintf('$this->lambdaHelper->withDelimiters(%s)', $delimTag);
$delims = ', ' . $delimTag;
} else {
$helper = '$this->lambdaHelper';
$delims = '';
}
$key = ucfirst(md5($delims . "\n" . $source));
if (!isset($this->sections[$key])) {
$this->sections[$key] = sprintf($this->prepare(self::SECTION), $key, $callable, $source, $helper, $delims, $this->walk($nodes, 2));
}
$method = $this->getFindMethod($id);
$id = var_export($id, true);
$filters = $this->getFilters($filters, $level);
return sprintf($this->prepare(self::SECTION_CALL, $level), $id, $method, $id, $filters, $key);
} | Base | 1 |
public function editTitle() {
global $user;
$file = new expFile($this->params['id']);
if ($user->id==$file->poster || $user->isAdmin()) {
$file->title = $this->params['newValue'];
$file->save();
$ar = new expAjaxReply(200, gt('Your title was updated successfully'), $file);
} else {
$ar = new expAjaxReply(300, gt("You didn't create this file, so you can't edit it."));
}
$ar->send();
} | Base | 1 |
foreach ($days as $value) {
$regitem[] = $value;
}
| Base | 1 |
public function createComment($id, $source = "leaves/leaves"){
$this->auth->checkIfOperationIsAllowed('view_leaves');
$data = getUserContext($this);
$oldComment = $this->leaves_model->getCommentsLeave($id);
$newComment = new stdClass;
$newComment->type = "comment";
$newComment->author = $this->session->userdata('id');
$newComment->value = $this->input->post('comment');
$newComment->date = date("Y-n-j");
if ($oldComment != NULL){
array_push($oldComment->comments, $newComment);
}else {
$oldComment = new stdClass;
$oldComment->comments = array($newComment);
}
$json = json_encode($oldComment);
$this->leaves_model->addComments($id, $json);
if(isset($_GET['source'])){
$source = $_GET['source'];
}
redirect("/$source/$id");
} | Base | 1 |
private function getSwimlane()
{
$swimlane = $this->swimlaneModel->getById($this->request->getIntegerParam('swimlane_id'));
if (empty($swimlane)) {
throw new PageNotFoundException();
}
return $swimlane;
} | Base | 1 |
protected function _copy($source, $targetDir, $name)
{
$res = false;
$target = $this->_joinPath($targetDir, $name);
if ($this->tmp) {
$local = $this->getTempFile();
if ($this->connect->get($source, $local)
&& $this->connect->put($target, $local, NET_SFTP_LOCAL_FILE)) {
$res = true;
}
unlink($local);
} else {
//not memory efficient
$res = $this->_filePutContents($target, $this->_getContents($source));
}
return $res;
} | Base | 1 |
public function clean($html) {
$antiXss = new \voku\helper\AntiXSS();
$html = $antiXss->xss_clean($html);
$config = \HTMLPurifier_Config::createDefault();
if ($this->purifierPath) {
$config->set('Cache.SerializerPath', $this->purifierPath);
}
if ($this->purifierPath) {
$config->set('Cache.SerializerPath', $this->purifierPath);
}
$config->set('URI.DisableExternal', true);
$config->set('URI.DisableExternalResources', true);
// $config->set('URI.DisableResources', true);
$config->set('URI.Host', site_hostname());
$purifier = new \HTMLPurifier($config);
$html = $purifier->purify($html);
return $html;
} | Base | 1 |
function manage_upcharge() {
$this->loc->src = "@globalstoresettings";
$config = new expConfig($this->loc);
$this->config = $config->config;
$gc = new geoCountry();
$countries = $gc->find('all');
$gr = new geoRegion();
$regions = $gr->find('all',null,'rank asc,name asc');
assign_to_template(array(
'countries'=>$countries,
'regions'=>$regions,
'upcharge'=>!empty($this->config['upcharge'])?$this->config['upcharge']:''
));
} | Class | 2 |
public static function validatePMAStorage($path, $values)
{
$result = array(
'Server_pmadb' => '',
'Servers/1/controluser' => '',
'Servers/1/controlpass' => ''
);
$error = false;
if ($values['Servers/1/pmadb'] == '') {
return $result;
}
$result = array();
if ($values['Servers/1/controluser'] == '') {
$result['Servers/1/controluser'] = __(
'Empty phpMyAdmin control user while using phpMyAdmin configuration '
. 'storage!'
);
$error = true;
}
if ($values['Servers/1/controlpass'] == '') {
$result['Servers/1/controlpass'] = __(
'Empty phpMyAdmin control user password while using phpMyAdmin '
. 'configuration storage!'
);
$error = true;
}
if (! $error) {
$test = static::testDBConnection(
$values['Servers/1/connect_type'],
$values['Servers/1/host'], $values['Servers/1/port'],
$values['Servers/1/socket'], $values['Servers/1/controluser'],
$values['Servers/1/controlpass'], 'Server_pmadb'
);
if ($test !== true) {
$result = array_merge($result, $test);
}
}
return $result;
} | Class | 2 |
public function actionPublishPost() {
$post = new Events;
// $user = $this->loadModel($id);
if (isset($_POST['text']) && $_POST['text'] != "") {
$post->text = $_POST['text'];
$post->visibility = $_POST['visibility'];
if (isset($_POST['associationId']))
$post->associationId = $_POST['associationId'];
//$soc->attributes = $_POST['Social'];
//die(var_dump($_POST['Social']));
$post->user = Yii::app()->user->getName();
$post->type = 'feed';
$post->subtype = $_POST['subtype'];
$post->lastUpdated = time();
$post->timestamp = time();
if ($post->save()) {
if (!empty($post->associationId) && $post->associationId != Yii::app()->user->getId()) {
$notif = new Notification;
$notif->type = 'social_post';
$notif->createdBy = $post->user;
$notif->modelType = 'Profile';
$notif->modelId = $post->associationId;
$notif->user = Yii::app()->db->createCommand()
->select('username')
->from('x2_users')
->where('id=:id', array(':id' => $post->associationId))
->queryScalar();
// $prof = X2Model::model('Profile')->findByAttributes(array('username'=>$post->user));
// $notif->text = "$prof->fullName posted on your profile.";
// $notif->record = "profile:$prof->id";
// $notif->viewed = 0;
$notif->createDate = time();
// $subject=X2Model::model('Profile')->findByPk($id);
// $notif->user = $subject->username;
$notif->save();
}
}
}
} | Base | 1 |
public function testRemoveAuthorizationHeaderOnRedirect()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
static function (RequestInterface $request) {
self::assertFalse($request->hasHeader('Authorization'));
return new Response(200);
}
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass']]);
} | Class | 2 |
public function Login ($username = '', $password = '') {
if ($this->connected == false) {
$this->error = 'Not connected to POP3 server';
if ($this->do_debug >= 1) {
$this->displayErrors();
}
}
if (empty($username)) {
$username = $this->username;
}
if (empty($password)) {
$password = $this->password;
}
$pop_username = "USER $username" . $this->CRLF;
$pop_password = "PASS $password" . $this->CRLF;
// Send the Username
$this->sendString($pop_username);
$pop3_response = $this->getResponse();
if ($this->checkResponse($pop3_response)) {
// Send the Password
$this->sendString($pop_password);
$pop3_response = $this->getResponse();
if ($this->checkResponse($pop3_response)) {
return true;
}
}
return false;
} | Class | 2 |
public static function dplParserFunction( &$parser ) {
self::setLikeIntersection( false );
$parser->addTrackingCategory( 'dpl-parserfunc-tracking-category' );
// callback for the parser function {{#dpl: or {{DynamicPageList::
$input = "";
$numargs = func_num_args();
if ( $numargs < 2 ) {
$input = "#dpl: no arguments specified";
return str_replace( '§', '<', '§pre>§nowiki>' . $input . '§/nowiki>§/pre>' );
}
// fetch all user-provided arguments (skipping $parser)
$arg_list = func_get_args();
for ( $i = 1; $i < $numargs; $i++ ) {
$p1 = $arg_list[$i];
$input .= str_replace( "\n", "", $p1 ) . "\n";
}
$parse = new \DPL\Parse();
$dplresult = $parse->parse( $input, $parser, $reset, $eliminate, false );
return [ // parser needs to be coaxed to do further recursive processing
$parser->getPreprocessor()->preprocessToObj( $dplresult, Parser::PTD_FOR_INCLUSION ),
'isLocalObj' => true,
'title' => $parser->getTitle()
];
} | Class | 2 |
public function testNoAuthorityWithInvalidPath()
{
$input = 'urn://example:animal:ferret:nose';
$uri = new Uri($input);
} | Base | 1 |
public function __construct () {
}
| Base | 1 |
foreach ($page as $pageperm) {
if (!empty($pageperm['manage'])) return true;
}
| Base | 1 |
public static function html() {
new Xaptcha();
$html = "<div class=\"form-group\">
<div class=\"g-recaptcha\" data-sitekey=\"".self::$key."\"></div></div>
<script type=\"text/javascript\"
src=\"https://www.google.com/recaptcha/api.js?hl=".self::$lang."\" async defer>
</script>";
if (self::isEnable()) {
return $html;
}else{
return '';
}
}
| Base | 1 |
$contents = ['form' => tep_draw_form('languages', 'languages.php', 'page=' . $_GET['page'] . '&lID=' . $lInfo->languages_id . '&action=save')]; | Base | 1 |
function send_feedback() {
$success = false;
if (isset($this->params['id'])) {
$ed = new eventdate($this->params['id']);
// $email_addrs = array();
if ($ed->event->feedback_email != '') {
$msgtemplate = expTemplate::get_template_for_action($this, 'email/_' . $this->params['formname'], $this->loc);
$msgtemplate->assign('params', $this->params);
$msgtemplate->assign('event', $ed);
$email_addrs = explode(',', $ed->event->feedback_email);
//This is an easy way to remove duplicates
$email_addrs = array_flip(array_flip($email_addrs));
$email_addrs = array_map('trim', $email_addrs);
$mail = new expMail();
$success += $mail->quickSend(array(
"text_message" => $msgtemplate->render(),
'to' => $email_addrs,
'from' => !empty($this->params['email']) ? $this->params['email'] : trim(SMTP_FROMADDRESS),
'subject' => $this->params['subject'],
));
}
}
if ($success) {
flashAndFlow('message', gt('Your feedback was successfully sent.'));
} else {
flashAndFlow('error', gt('We could not send your feedback. Please contact your administrator.'));
}
}
| Base | 1 |
public function Connect ($host, $port = false, $tval = 30) {
// Are we already connected?
if ($this->connected) {
return true;
}
/*
On Windows this will raise a PHP Warning error if the hostname doesn't exist.
Rather than supress it with @fsockopen, let's capture it cleanly instead
*/
set_error_handler(array(&$this, 'catchWarning'));
// Connect to the POP3 server
$this->pop_conn = fsockopen($host, // POP3 Host
$port, // Port #
$errno, // Error Number
$errstr, // Error Message
$tval); // Timeout (seconds)
// Restore the error handler
restore_error_handler();
// Does the Error Log now contain anything?
if ($this->error && $this->do_debug >= 1) {
$this->displayErrors();
}
// Did we connect?
if ($this->pop_conn == false) {
// It would appear not...
$this->error = array(
'error' => "Failed to connect to server $host on port $port",
'errno' => $errno,
'errstr' => $errstr
);
if ($this->do_debug >= 1) {
$this->displayErrors();
}
return false;
}
// Increase the stream time-out
// Check for PHP 4.3.0 or later
if (version_compare(phpversion(), '5.0.0', 'ge')) {
stream_set_timeout($this->pop_conn, $tval, 0);
} else {
// Does not work on Windows
if (substr(PHP_OS, 0, 3) !== 'WIN') {
socket_set_timeout($this->pop_conn, $tval, 0);
}
}
// Get the POP3 server response
$pop3_response = $this->getResponse();
// Check for the +OK
if ($this->checkResponse($pop3_response)) {
// The connection is established and the POP3 server is talking
$this->connected = true;
return true;
}
return false;
} | Base | 1 |
public function show()
{
$task = $this->getTask();
$subtask = $this->getSubtask();
$this->response->html($this->template->render('subtask_restriction/show', array(
'status_list' => array(
SubtaskModel::STATUS_TODO => t('Todo'),
SubtaskModel::STATUS_DONE => t('Done'),
),
'subtask_inprogress' => $this->subtaskStatusModel->getSubtaskInProgress($this->userSession->getId()),
'subtask' => $subtask,
'task' => $task,
)));
} | Base | 1 |
public static function getParent($parent='', $menuid = ''){
if(isset($menuid)){
$where = " AND `menuid` = '{$menuid}'";
}else{
$where = '';
}
$sql = sprintf("SELECT * FROM `menus` WHERE `parent` = '%s' %s", $parent, $where);
$menu = Db::result($sql);
return $menu;
} | Base | 1 |
function deleteAllCustomDNSEntries()
{
$handle = fopen($customDNSFile, "r");
if ($handle)
{
try
{
while (($line = fgets($handle)) !== false) {
$line = str_replace("\r","", $line);
$line = str_replace("\n","", $line);
$explodedLine = explode (" ", $line);
if (count($explodedLine) != 2)
continue;
$ip = $explodedLine[0];
$domain = $explodedLine[1];
pihole_execute("-a removecustomdns ".$ip." ".$domain);
}
}
catch (\Exception $ex)
{
return errorJsonResponse($ex->getMessage());
}
fclose($handle);
}
return successJsonResponse();
} | Class | 2 |
foreach ($allusers as $uid) {
$u = user::getUserById($uid);
expPermissions::grant($u, 'manage', $sloc);
}
| Base | 1 |
public function saveLdapConfig(){
$login_user = $this->checkLogin();
$this->checkAdmin();
$ldap_open = intval(I("ldap_open")) ;
$ldap_form = I("ldap_form") ;
if ($ldap_open) {
if (!$ldap_form['user_field']) {
$ldap_form['user_field'] = 'cn';
}
if( !extension_loaded( 'ldap' ) ) {
$this->sendError(10011,"你尚未安装php-ldap扩展。如果是普通PHP环境,请手动安装之。如果是使用之前官方docker镜像,则需要重新安装镜像。方法是:备份 /showdoc_data 整个目录,然后全新安装showdoc,接着用备份覆盖/showdoc_data 。然后递归赋予777可写权限。");
return ;
}
$ldap_conn = ldap_connect($ldap_form['host'], $ldap_form['port']);//建立与 LDAP 服务器的连接
if (!$ldap_conn) {
$this->sendError(10011,"Can't connect to LDAP server");
return ;
}
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, $ldap_form['version']);
$rs=ldap_bind($ldap_conn, $ldap_form['bind_dn'], $ldap_form['bind_password']);//与服务器绑定 用户登录验证 成功返回1
if (!$rs) {
$this->sendError(10011,"Can't bind to LDAP server");
return ;
}
$result = ldap_search($ldap_conn,$ldap_form['base_dn'],"(cn=*)");
$data = ldap_get_entries($ldap_conn, $result);
for ($i=0; $i<$data["count"]; $i++) {
$ldap_user = $data[$i][$ldap_form['user_field']][0] ;
if (!$ldap_user) {
continue ;
}
//如果该用户不在数据库里,则帮助其注册
if(!D("User")->isExist($ldap_user)){
D("User")->register($ldap_user,$ldap_user.time());
}
}
D("Options")->set("ldap_form" , json_encode( $ldap_form)) ;
}
D("Options")->set("ldap_open" ,$ldap_open) ;
$this->sendResult(array());
} | Base | 1 |
public static function login() {
user::login(expString::sanitize($_POST['username']),expString::sanitize($_POST['password']));
if (!isset($_SESSION[SYS_SESSION_KEY]['user'])) { // didn't successfully log in
flash('error', gt('Invalid Username / Password'));
if (expSession::is_set('redirecturl_error')) {
$url = expSession::get('redirecturl_error');
expSession::un_set('redirecturl_error');
header("Location: ".$url);
} else {
expHistory::back();
}
} else { // we're logged in
global $user;
if (expSession::get('customer-login')) expSession::un_set('customer-login');
if (!empty($_POST['username'])) flash('message', gt('Welcome back').' '.expString::sanitize($_POST['username']));
if ($user->isAdmin()) {
expHistory::back();
} else {
foreach ($user->groups as $g) {
if (!empty($g->redirect)) {
$url = URL_FULL.$g->redirect;
break;
}
}
if (isset($url)) {
header("Location: ".$url);
} else {
expHistory::back();
}
}
}
} | Base | 1 |
static function displayname() {
return gt("e-Commerce Category Manager");
} | Base | 1 |
private static function _aesEncrypt($data, $secret)
{
if (!is_string($data)) {
throw new \InvalidArgumentException('Input parameter "$data" must be a string.');
}
if (!function_exists("openssl_encrypt")) {
throw new \SimpleSAML_Error_Exception('The openssl PHP module is not loaded.');
}
$raw = defined('OPENSSL_RAW_DATA') ? OPENSSL_RAW_DATA : true;
$key = openssl_digest($secret, 'sha256');
$method = 'AES-256-CBC';
$ivSize = 16;
$iv = substr($key, 0, $ivSize);
return $iv.openssl_encrypt($data, $method, $key, $raw, $iv);
} | Class | 2 |
foreach ($day as $extevent) {
$event_cache = new stdClass();
$event_cache->feed = $extgcalurl;
$event_cache->event_id = $extevent->event_id;
$event_cache->title = $extevent->title;
$event_cache->body = $extevent->body;
$event_cache->eventdate = $extevent->eventdate->date;
if (isset($extevent->dateFinished) && $extevent->dateFinished != -68400)
$event_cache->dateFinished = $extevent->dateFinished;
if (isset($extevent->eventstart))
$event_cache->eventstart = $extevent->eventstart;
if (isset($extevent->eventend))
$event_cache->eventend = $extevent->eventend;
if (isset($extevent->is_allday))
$event_cache->is_allday = $extevent->is_allday;
$found = false;
if ($extevent->eventdate->date < $start) // prevent duplicating events crossing month boundaries
$found = $db->selectObject('event_cache','feed="'.$extgcalurl.'" AND event_id="'.$event_cache->event_id.'" AND eventdate='.$event_cache->eventdate);
if (!$found)
$db->insertObject($event_cache,'event_cache');
}
| Base | 1 |
function process_subsections($parent_section, $subtpl) {
global $db, $router;
$section = new stdClass();
$section->parent = $parent_section->id;
$section->name = $subtpl->name;
$section->sef_name = $router->encode($section->name);
$section->subtheme = $subtpl->subtheme;
$section->active = $subtpl->active;
$section->public = $subtpl->public;
$section->rank = $subtpl->rank;
$section->page_title = $subtpl->page_title;
$section->keywords = $subtpl->keywords;
$section->description = $subtpl->description;
$section->id = $db->insertObject($section, 'section');
self::process_section($section, $subtpl);
}
| Base | 1 |
public function isAllowedFilename($filename){
$allow_array = array(
'.jpg','.jpeg','.png','.bmp','.gif','.ico','.webp',
'.mp3','.wav','.m4a','.ogg','.webma','.mp4','.flv',
'.mov','.webmv','.m3u8a','.flac','.mkv',
'.zip','.tar','.gz','.tgz','.ipa','.apk','.rar','.iso','.bz2','.epub',
'.pdf','.ofd','.swf','.epub','.xps',
'.doc','.docx','.odt','.rtf','.docm','.dotm','.dot','.dotx','.wps','.wpt',
'.ppt','.pptx','.xls','.xlsx','.txt','.md','.psd','.csv',
'.cer','.ppt','.pub','.properties','.json','.css',
) ;
$ext = strtolower(substr($filename,strripos($filename,'.')) ); //获取文件扩展名(转为小写后)
if(in_array( $ext , $allow_array ) ){
return true ;
}
return false;
} | Base | 1 |
public function get($id)
{
if (!is_numeric($id)) {
$this->errors[] = _T("ID must be an integer!");
return false;
}
try {
$select = $this->zdb->select($this->table);
$select->where($this->fpk . '=' . $id);
$results = $this->zdb->execute($select);
$result = $results->current();
if (!$result) {
$this->errors[] = _T("Label does not exist");
return false;
}
return $result;
} catch (Throwable $e) {
Analog::log(
__METHOD__ . ' | ' . $e->getMessage(),
Analog::WARNING
);
throw $e;
}
} | Base | 1 |
public function getSelectorsBySpecificity($sSpecificitySearch = null) {
if (is_numeric($sSpecificitySearch) || is_numeric($sSpecificitySearch[0])) {
$sSpecificitySearch = "== $sSpecificitySearch";
}
$aResult = array();
$this->allSelectors($aResult, $sSpecificitySearch);
return $aResult;
} | Base | 1 |
public static function checkPermissions($permission,$location) {
global $exponent_permissions_r, $router;
// only applies to the 'manage' method
if (empty($location->src) && empty($location->int) && (!empty($router->params['action']) && $router->params['action'] == 'manage') || strpos($router->current_url, 'action=manage') !== false) {
if (!empty($exponent_permissions_r['navigation'])) foreach ($exponent_permissions_r['navigation'] as $page) {
foreach ($page as $pageperm) {
if (!empty($pageperm['manage'])) return true;
}
}
}
return false;
}
| Base | 1 |
$item = array();
$item['id'] = $incident->id;
$item['title'] = $incident->incident_title;
$item['link'] = $site_url.'reports/view/'.$incident->id;
$item['description'] = $incident->incident_description;
$item['date'] = $incident->incident_date;
$item['categories'] = $categories;
if
(
$incident->location_id != 0 AND
$incident->location->longitude AND
$incident->location->latitude
)
{
$item['point'] = array(
$incident->location->latitude,
$incident->location->longitude
);
$items[] = $item;
}
}
$cache->set($subdomain.'_feed_'.$limit.'_'.$page, $items, array('feed'), 3600); // 1 Hour
$feed_items = $items;
}
$feedpath = $feedtype == 'atom' ? 'feed/atom/' : 'feed/';
//header("Content-Type: text/xml; charset=utf-8");
$view = new View('feed/'.$feedtype);
$view->feed_title = htmlspecialchars(Kohana::config('settings.site_name'));
$view->site_url = $site_url;
$view->georss = 1; // this adds georss namespace in the feed
$view->feed_url = $site_url.$feedpath;
$view->feed_date = gmdate("D, d M Y H:i:s T", time());
$view->feed_description = htmlspecialchars(Kohana::lang('ui_admin.incident_feed').' '.Kohana::config('settings.site_name'));
$view->items = $feed_items;
$view->render(TRUE);
} | Base | 1 |
public function update()
{
$project = $this->getProject();
$tag_id = $this->request->getIntegerParam('tag_id');
$tag = $this->tagModel->getById($tag_id);
$values = $this->request->getValues();
list($valid, $errors) = $this->tagValidator->validateModification($values);
if ($tag['project_id'] != $project['id']) {
throw new AccessForbiddenException();
}
if ($valid) {
if ($this->tagModel->update($values['id'], $values['name'])) {
$this->flash->success(t('Tag updated successfully.'));
} else {
$this->flash->failure(t('Unable to update this tag.'));
}
$this->response->redirect($this->helper->url->to('ProjectTagController', 'index', array('project_id' => $project['id'])));
} else {
$this->edit($values, $errors);
}
} | Base | 1 |
function preview()
{
if ($this->params['id'] == 0) { // we want the default editor
$demo = new stdClass();
$demo->id = 0;
$demo->name = "Default";
if ($this->params['editor'] == 'ckeditor') {
$demo->skin = 'kama';
} elseif ($this->params['editor'] == 'tinymce') {
$demo->skin = 'lightgray';
}
} else {
$demo = self::getEditorSettings($this->params['id'], expString::escape($this->params['editor']));
}
assign_to_template(
array(
'demo' => $demo,
'editor' => $this->params['editor']
)
);
} | Base | 1 |
PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['LogoutURL']);
} else {
PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['SignonURL']);
}
if (!defined('TESTSUITE')) {
exit();
} else {
return false;
}
} | Class | 2 |
public function backup($type='json')
{
global $DB;
global $website;
$out = array();
$DB->query('SELECT * FROM nv_properties WHERE website = '.protect($website->id), 'object');
if($type='json')
$out['nv_properties'] = json_encode($DB->result());
$DB->query('SELECT * FROM nv_properties_items WHERE website = '.protect($website->id), 'object');
if($type='json')
$out['nv_properties_items'] = json_encode($DB->result());
if($type='json')
$out = json_encode($out);
return $out;
}
| Base | 1 |
protected function renderImageByImagick($code)
{
$backColor = $this->transparent ? new \ImagickPixel('transparent') : new \ImagickPixel('#' . str_pad(dechex($this->backColor), 6, 0, STR_PAD_LEFT));
$foreColor = new \ImagickPixel('#' . str_pad(dechex($this->foreColor), 6, 0, STR_PAD_LEFT));
$image = new \Imagick();
$image->newImage($this->width, $this->height, $backColor);
$draw = new \ImagickDraw();
$draw->setFont($this->fontFile);
$draw->setFontSize(30);
$fontMetrics = $image->queryFontMetrics($draw, $code);
$length = strlen($code);
$w = (int) $fontMetrics['textWidth'] - 8 + $this->offset * ($length - 1);
$h = (int) $fontMetrics['textHeight'] - 8;
$scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
$x = 10;
$y = round($this->height * 27 / 40);
for ($i = 0; $i < $length; ++$i) {
$draw = new \ImagickDraw();
$draw->setFont($this->fontFile);
$draw->setFontSize((int) (mt_rand(26, 32) * $scale * 0.8));
$draw->setFillColor($foreColor);
$image->annotateImage($draw, $x, $y, mt_rand(-10, 10), $code[$i]);
$fontMetrics = $image->queryFontMetrics($draw, $code[$i]);
$x += (int) $fontMetrics['textWidth'] + $this->offset;
}
$image->setImageFormat('png');
return $image->getImageBlob();
} | Class | 2 |
public function boot()
{
// Configure the debugbar
Config::set('debugbar', Config::get('rainlab.debugbar::config'));
// Service provider
App::register('\Barryvdh\Debugbar\ServiceProvider');
// Register alias
$alias = AliasLoader::getInstance();
$alias->alias('Debugbar', '\Barryvdh\Debugbar\Facade');
// Register middleware
if (Config::get('app.debugAjax', false)) {
$this->app['Illuminate\Contracts\Http\Kernel']->pushMiddleware('\RainLab\Debugbar\Middleware\Debugbar');
}
Event::listen('cms.page.beforeDisplay', function ($controller, $url, $page) {
// Only show for authenticated backend users
if (!BackendAuth::check()) {
Debugbar::disable();
}
// Twig extensions
$twig = $controller->getTwig();
if (!$twig->hasExtension(\Barryvdh\Debugbar\Twig\Extension\Debug::class)) {
$twig->addExtension(new \Barryvdh\Debugbar\Twig\Extension\Debug($this->app));
$twig->addExtension(new \Barryvdh\Debugbar\Twig\Extension\Stopwatch($this->app));
}
});
} | Base | 1 |
$newret = recyclebin::restoreFromRecycleBin($iLoc, $page_id);
if (!empty($newret)) $ret .= $newret . '<br>';
if ($iLoc->mod == 'container') {
$ret .= scan_container($container->internal, $page_id);
}
}
return $ret;
}
| Class | 2 |
public function confirm()
{
$project = $this->getProject();
$swimlane = $this->getSwimlane();
$this->response->html($this->helper->layout->project('swimlane/remove', array(
'project' => $project,
'swimlane' => $swimlane,
)));
} | Base | 1 |
public function testGetFilesWithBrokenSetup() {
$location = '';
$features = '';
$etag = 1111222233334444;
$mediatypes = 'image/png';
$exceptionMessage = 'Aïe!';
$this->searchFolderService->expects($this->once())
->method('getCurrentFolder')
->with(
$location,
[$features]
)
->willThrowException(new ServiceException($exceptionMessage));
// Default status code when something breaks
$status = Http::STATUS_INTERNAL_SERVER_ERROR;
$errorMessage = [
'message' => $exceptionMessage . ' (' . $status . ')',
'success' => false
];
/** @type JSONResponse $response */
$response = $this->controller->getList($location, $features, $etag, $mediatypes);
$this->assertEquals($errorMessage, $response->getData());
} | Base | 1 |
public function setScriptSrc(Response $response)
{
if (config('app.allow_content_scripts')) {
return;
}
$parts = [
'http:',
'https:',
'\'nonce-' . $this->nonce . '\'',
'\'strict-dynamic\'',
];
$value = 'script-src ' . implode(' ', $parts);
$response->headers->set('Content-Security-Policy', $value, false);
} | Base | 1 |
public function gc($force = false, $expiredOnly = true)
{
if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
$this->gcRecursive($this->cachePath, $expiredOnly);
}
} | Class | 2 |
public function execute()
{
parent::execute();
// get parameters
$term = SpoonFilter::getPostValue('term', null, '');
// validate
if($term == '') $this->output(self::BAD_REQUEST, null, 'term-parameter is missing.');
// previous search result
$previousTerm = SpoonSession::exists('searchTerm') ? SpoonSession::get('searchTerm') : '';
SpoonSession::set('searchTerm', '');
// save this term?
if($previousTerm != $term)
{
// format data
$this->statistics = array();
$this->statistics['term'] = $term;
$this->statistics['language'] = FRONTEND_LANGUAGE;
$this->statistics['time'] = FrontendModel::getUTCDate();
$this->statistics['data'] = serialize(array('server' => $_SERVER));
$this->statistics['num_results'] = FrontendSearchModel::getTotal($term);
// save data
FrontendSearchModel::save($this->statistics);
}
// save current search term in cookie
SpoonSession::set('searchTerm', $term);
// output
$this->output(self::OK);
} | Base | 1 |
public function delete($id)
{
if ($this->securityController->isWikiHibernated()) {
throw new \Exception(_t('WIKI_IN_HIBERNATION'));
}
// tests of if $formId is int
if (strval(intval($id)) != strval($id)) {
return null ;
}
$this->clear($id);
return $this->dbService->query('DELETE FROM ' . $this->dbService->prefixTable('nature') . 'WHERE bn_id_nature=' . $id);
} | Base | 1 |
private function getTaskLink()
{
$link = $this->taskLinkModel->getById($this->request->getIntegerParam('link_id'));
if (empty($link)) {
throw new PageNotFoundException();
}
return $link;
} | Base | 1 |
public function manage()
{
expHistory::set('manageable',$this->params);
$gc = new geoCountry();
$countries = $gc->find('all');
$gr = new geoRegion();
$regions = $gr->find('all',null,'rank asc,name asc');
assign_to_template(array(
'countries'=>$countries,
'regions'=>$regions
));
} | Class | 2 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.