code
stringlengths 12
2.05k
| label_name
stringclasses 5
values | label
int64 0
4
|
---|---|---|
public function destroy($id)
{
$sql = 'DELETE FROM plugin_hudson_widget WHERE id = ' . $id . ' AND owner_id = ' . $this->owner_id . " AND owner_type = '" . $this->owner_type . "'";
db_query($sql);
} | Base | 1 |
foreach ($nodes as $node) {
if ((($perm == 'view' && $node->public == 1) || expPermissions::check($perm, expCore::makeLocation('navigation', '', $node->id))) && !in_array($node->id, $ignore_ids)) {
if ($node->active == 1) {
$text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . $node->name;
} else {
$text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . '(' . $node->name . ')';
}
$ar[$node->id] = $text;
foreach (self::levelDropdownControlArray($node->id, $depth + 1, $ignore_ids, $full, $perm, $addstandalones, $addinternalalias) as $id => $text) {
$ar[$id] = $text;
}
}
}
| Base | 1 |
$navs[$i]->link = expCore::makeLink(array('section' => $navs[$i]->id), '', $navs[$i]->sef_name);
if (!$view) {
// unset($navs[$i]); //FIXME this breaks jstree if we remove a parent and not the child
$attr = new stdClass();
$attr->class = 'hidden'; // bs3 class to hide elements
$navs[$i]->li_attr = $attr;
}
}
| Base | 1 |
protected function _mkfile($path, $name)
{
$path = $this->_joinPath($path, $name);
return $this->connect->put($path, '') ? $path : false;
/*
if ($this->tmp) {
$path = $this->_joinPath($path, $name);
$local = $this->getTempFile();
$res = touch($local) && $this->connect->put($path, $local, NET_SFTP_LOCAL_FILE);
unlink($local);
return $res ? $path : false;
}
return false;
*/
} | Base | 1 |
} elseif ( $sSecLabel[0] != '{' ) {
$limpos = strpos( $sSecLabel, '[' );
$cutLink = 'default';
$skipPattern = [];
if ( $limpos > 0 && $sSecLabel[strlen( $sSecLabel ) - 1] == ']' ) {
// regular expressions which define a skip pattern may precede the text
$fmtSec = explode( '~', substr( $sSecLabel, $limpos + 1, strlen( $sSecLabel ) - $limpos - 2 ) );
$sSecLabel = substr( $sSecLabel, 0, $limpos );
$cutInfo = explode( " ", $fmtSec[count( $fmtSec ) - 1], 2 );
$maxLength = intval( $cutInfo[0] );
if ( array_key_exists( '1', $cutInfo ) ) {
$cutLink = $cutInfo[1];
}
foreach ( $fmtSec as $skipKey => $skipPat ) {
if ( $skipKey == count( $fmtSec ) - 1 ) {
continue;
}
$skipPattern[] = $skipPat;
}
}
if ( $maxLength < 0 ) {
$maxLength = -1; // without valid limit include whole section
}
} | Class | 2 |
function readline(StreamInterface $stream, $maxLength = null)
{
$buffer = '';
$size = 0;
while (!$stream->eof()) {
// Using a loose equality here to match on '' and false.
if (null == ($byte = $stream->read(1))) {
return $buffer;
}
$buffer .= $byte;
// Break when a new line is found or the max length - 1 is reached
if ($byte == PHP_EOL || ++$size == $maxLength - 1) {
break;
}
}
return $buffer;
} | Base | 1 |
function load_gallery($auc_id)
{
$UPLOADED_PICTURES = array();
if (is_dir(UPLOAD_PATH . $auc_id)) {
if ($dir = opendir(UPLOAD_PATH . $auc_id)) {
while ($file = @readdir($dir)) {
if ($file != '.' && $file != '..' && strpos($file, 'thumb-') === false) {
$UPLOADED_PICTURES[] = UPLOAD_FOLDER . $auc_id . '/' . $file;
}
}
closedir($dir);
}
}
return $UPLOADED_PICTURES;
} | Base | 1 |
$chrootPath = realpath($chrootPath);
if ($chrootPath !== false && strpos($realfile, $chrootPath) === 0) {
$chrootValid = true;
break;
}
}
if ($chrootValid !== true) {
Helpers::record_warnings(E_USER_WARNING, "Permission denied on $file. The file could not be found under the paths specified by Options::chroot.", __FILE__, __LINE__);
return;
}
}
if (!$realfile) {
Helpers::record_warnings(E_USER_WARNING, "File '$realfile' not found.", __FILE__, __LINE__);
return;
}
$file = $realfile;
}
[$css, $http_response_header] = Helpers::getFileContent($file, $this->_dompdf->getHttpContext());
$good_mime_type = true;
// See http://the-stickman.com/web-development/php/getting-http-response-headers-when-using-file_get_contents/
if (isset($http_response_header) && !$this->_dompdf->getQuirksmode()) {
foreach ($http_response_header as $_header) {
if (preg_match("@Content-Type:\s*([\w/]+)@i", $_header, $matches) &&
($matches[1] !== "text/css")
) {
$good_mime_type = false;
}
}
}
if (!$good_mime_type || $css === null) {
Helpers::record_warnings(E_USER_WARNING, "Unable to load css file $file", __FILE__, __LINE__);
return;
}
}
$this->_parse_css($css);
} | Base | 1 |
public function configure() {
$this->config['defaultbanner'] = array();
if (!empty($this->config['defaultbanner_id'])) {
$this->config['defaultbanner'][] = new expFile($this->config['defaultbanner_id']);
}
parent::configure();
$banners = $this->banner->find('all', null, 'companies_id');
assign_to_template(array(
'banners'=>$banners,
'title'=>static::displayname()
));
} | Base | 1 |
public function addAddress($address, $name = '')
{
return $this->addAnAddress('to', $address, $name);
} | Compound | 4 |
public static function lists($vars) {
return Categories::lists($vars);
}
| Base | 1 |
protected function markCompleted($endStatus, ServiceResponse $serviceResponse, $gatewayMessage)
{
parent::markCompleted($endStatus, $serviceResponse, $gatewayMessage);
$this->createMessage(Message\CreateCardResponse::class, $gatewayMessage);
ErrorHandling::safeExtend($this->payment, 'onCardCreated', $serviceResponse);
} | Class | 2 |
public static function parseAndTrimImport($str, $isHTML = false) { //�Death from above�? �
//echo "1<br>"; eDebug($str);
// global $db;
$str = str_replace("�", "’", $str);
$str = str_replace("�", "‘", $str);
$str = str_replace("�", "®", $str);
$str = str_replace("�", "-", $str);
$str = str_replace("�", "—", $str);
$str = str_replace("�", "”", $str);
$str = str_replace("�", "“", $str);
$str = str_replace("\r\n", " ", $str);
$str = str_replace("\,", ",", $str);
$str = str_replace('""', '"', $str); //do this no matter what...in case someone added a quote in a non HTML field
if (!$isHTML) {
//if HTML, then leave the single quotes alone, otheriwse replace w/ special Char
$str = str_replace('"', """, $str);
}
$str = str_replace("�", "¼", $str);
$str = str_replace("�", "½", $str);
$str = str_replace("�", "¾", $str);
//$str = htmlspecialchars($str);
//$str = utf8_encode($str);
// if (DB_ENGINE=='mysqli') {
// $str = @mysqli_real_escape_string($db->connection,trim(str_replace("�", "™", $str)));
// } elseif(DB_ENGINE=='mysql') {
// $str = @mysql_real_escape_string(trim(str_replace("�", "™", $str)),$db->connection);
// } else {
// $str = trim(str_replace("�", "™", $str));
// }
$str = @expString::escape(trim(str_replace("�", "™", $str)));
//echo "2<br>"; eDebug($str,die);
return $str;
} | Base | 1 |
public function install () {
Session::start();
System::gZip();
Theme::install('header');
Control::handler('install');
Theme::install('footer');
System::Zipped();
}
| Base | 1 |
public function backup($type='json')
{
global $DB;
global $website;
$out = array();
$DB->query('SELECT * FROM nv_websites WHERE id = '.protect($website->id), 'object');
if($type='json')
$out = json_encode($DB->result());
return $out;
}
| Base | 1 |
public function __construct(App $app)
{
$this->Config = $app->Config;
$this->Request = $app->Request;
$this->Session = $app->Session;
} | Base | 1 |
public function testDoesNotAddPortWhenNoPort()
{
$this->assertEquals('bar', new Uri('//bar'));
$this->assertEquals('bar', (new Uri('//bar'))->getHost());
} | Base | 1 |
public function edit(Request $request, TransactionCurrency $currency)
{
/** @var User $user */
$user = auth()->user();
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(sprintf('Tried to edit currency %s but is not owner.', $currency->code));
return redirect(route('currencies.index'));
}
$subTitleIcon = 'fa-pencil';
$subTitle = (string) trans('breadcrumbs.edit_currency', ['name' => $currency->name]);
$currency->symbol = htmlentities($currency->symbol);
// code to handle active-checkboxes
$hasOldInput = null !== $request->old('_token');
$preFilled = [
'enabled' => $hasOldInput ? (bool) $request->old('enabled') : $currency->enabled,
];
$request->session()->flash('preFilled', $preFilled);
Log::channel('audit')->info('Edit currency.', $currency->toArray());
// put previous url in session if not redirect from store (not "return_to_edit").
if (true !== session('currencies.edit.fromUpdate')) {
$this->rememberPreviousUri('currencies.edit.uri');
}
$request->session()->forget('currencies.edit.fromUpdate');
return prefixView('currencies.edit', compact('currency', 'subTitle', 'subTitleIcon'));
} | Compound | 4 |
public function actionView($id) {
$model = CActiveRecord::model('Docs')->findByPk($id);
if (!$this->checkPermissions($model, 'view')) $this->denied ();
if(isset($model)){
$permissions=explode(", ",$model->editPermissions);
if(in_array(Yii::app()->user->getName(),$permissions))
$editFlag=true;
else
$editFlag=false;
}
//echo $model->visibility;exit;
if (!isset($model) ||
!(($model->visibility==1 ||
($model->visibility==0 && $model->createdBy==Yii::app()->user->getName())) ||
Yii::app()->params->isAdmin|| $editFlag))
$this->redirect(array('/docs/docs/index'));
// add doc to user's recent item list
User::addRecentItem('d', $id, Yii::app()->user->getId());
X2Flow::trigger('RecordViewTrigger',array('model'=>$model));
$this->render('view', array(
'model' => $model,
));
} | Base | 1 |
public function Quit($close_on_error = true) {
$this->error = null; // so there is no confusion
if(!$this->connected()) {
$this->error = array(
"error" => "Called Quit() without being connected");
return false;
}
// send the quit command to the server
fputs($this->smtp_conn,"quit" . $this->CRLF);
// get any good-bye messages
$byemsg = $this->get_lines();
if($this->do_debug >= 2) {
$this->edebug("SMTP -> FROM SERVER:" . $byemsg . $this->CRLF . '<br />');
}
$rval = true;
$e = null;
$code = substr($byemsg,0,3);
if($code != 221) {
// use e as a tmp var cause Close will overwrite $this->error
$e = array("error" => "SMTP server rejected quit command",
"smtp_code" => $code,
"smtp_rply" => substr($byemsg,4));
$rval = false;
if($this->do_debug >= 1) {
$this->edebug("SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '<br />');
}
}
if(empty($e) || $close_on_error) {
$this->Close();
}
return $rval;
} | Base | 1 |
public function routePostProvider()
{
return [
['/api/articles/', 1, 'articles', 'post', false],
['/api/v1/articles/', 1, 'articles', 'post', false],
['/api/v2/articles/', 2, 'articles', 'post', false],
['/api/articles/5', 1, 'articles', 'post', 5],
['/api/v1/articles/5', 1, 'articles', 'post', 5],
['/api/v2/articles/5', 2, 'articles', 'post', 5],
];
} | Base | 1 |
public function __construct()
{
parent::__construct();
// for flash data
$this->load->library('session');
if (!$this->fuel->config('admin_enabled')) show_404();
$this->load->vars(array(
'js' => '',
'css' => css($this->fuel->config('xtra_css')), // use CSS function here because of the asset library path changes below
'js_controller_params' => array(),
'keyboard_shortcuts' => $this->fuel->config('keyboard_shortcuts')));
// change assets path to admin
$this->asset->assets_path = $this->fuel->config('fuel_assets_path');
// set asset output settings
$this->asset->assets_output = $this->fuel->config('fuel_assets_output');
$this->lang->load('fuel');
$this->load->helper('ajax');
$this->load->library('form_builder');
$this->load->module_model(FUEL_FOLDER, 'fuel_users_model');
// set configuration paths for assets in case they are different from front end
$this->asset->assets_module ='fuel';
$this->asset->assets_folders = array(
'images' => 'images/',
'css' => 'css/',
'js' => 'js/',
);
} | Compound | 4 |
protected function getFile()
{
$task_id = $this->request->getIntegerParam('task_id');
$file_id = $this->request->getIntegerParam('file_id');
$model = 'projectFileModel';
if ($task_id > 0) {
$model = 'taskFileModel';
$project_id = $this->taskFinderModel->getProjectId($task_id);
if ($project_id !== $this->request->getIntegerParam('project_id')) {
throw new AccessForbiddenException();
}
}
$file = $this->$model->getById($file_id);
if (empty($file)) {
throw new PageNotFoundException();
}
$file['model'] = $model;
return $file;
} | Base | 1 |
public function getPurchaseOrderByJSON() {
if(!empty($this->params['vendor'])) {
$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);
} else {
$purchase_orders = $this->purchase_order->find('all');
}
echo json_encode($purchase_orders);
} | Class | 2 |
recyclebin::sendToRecycleBin($loc, $parent);
//FIXME if we delete the module & sectionref the module completely disappears
// if (class_exists($secref->module)) {
// $modclass = $secref->module;
// //FIXME: more module/controller glue code
// if (expModules::controllerExists($modclass)) {
// $modclass = expModules::getControllerClassName($modclass);
// $mod = new $modclass($loc->src);
// $mod->delete_instance();
// } else {
// $mod = new $modclass();
// $mod->deleteIn($loc);
// }
// }
}
// $db->delete('sectionref', 'section=' . $parent);
$db->delete('section', 'parent=' . $parent);
}
| Base | 1 |
public static function remove_all($object_type, $object_id)
{
global $DB;
global $website;
$DB->execute('
DELETE FROM nv_notes
WHERE website = '.protect($website->id).'
AND item_type = '.protect($object_type).'
AND item_id = '.protect($object_id).'
LIMIT 1'
);
return 'true';
}
| Base | 1 |
public function update()
{
$project = $this->getProject();
$values = $this->request->getValues();
list($valid, $errors) = $this->swimlaneValidator->validateModification($values);
if ($valid) {
if ($this->swimlaneModel->update($values['id'], $values)) {
$this->flash->success(t('Swimlane updated successfully.'));
return $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));
} else {
$errors = array('name' => array(t('Another swimlane with the same name exists in the project')));
}
}
return $this->edit($values, $errors);
} | Base | 1 |
function audit($method, $class, $statement, $formats, $values, $users_id) {
$this->method = $method;
$this->class = $class;
$this->statement = substr(str_replace("'", "", $statement),0,1000)."n";
$this->formats = $formats;
$this->values = $values;
$this->ip = getRealIpAddr();
$this->users_id = empty($users_id)?"NULL":$users_id;
return $this->save();
}
| Base | 1 |
public function umount() {
$this->connect && @ftp_close($this->connect);
} | Base | 1 |
public function remove()
{
$this->checkCSRFParam();
$project = $this->getProject();
$filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));
$this->checkPermission($project, $filter);
if ($this->customFilterModel->remove($filter['id'])) {
$this->flash->success(t('Custom filter removed successfully.'));
} else {
$this->flash->failure(t('Unable to remove this custom filter.'));
}
$this->response->redirect($this->helper->url->to('CustomFilterController', 'index', array('project_id' => $project['id'])));
} | Base | 1 |
public function add($array)
{
$this->db = array_merge($array, $this->db);
} | Base | 1 |
public static function get_param($key = NULL) {
$info = [
'stype' => self::$search_type,
'stext' => self::$search_text,
'method' => self::$search_method,
'datelimit' => self::$search_date_limit,
'fields' => self::$search_fields,
'sort' => self::$search_sort,
'chars' => self::$search_chars,
'order' => self::$search_order,
'forum_id' => self::$forum_id,
'memory_limit' => self::$memory_limit,
'composevars' => self::$composevars,
'rowstart' => self::$rowstart,
'search_param' => self::$search_param,
];
return $key === NULL ? $info : (isset($info[$key]) ? $info[$key] : NULL);
} | Compound | 4 |
public static function navtojson() {
return json_encode(self::navhierarchy());
}
| Base | 1 |
public function __construct() {
self::$key = Options::v('google_captcha_sitekey');
self::$secret = Options::v('google_captcha_secret');
self::$lang = Options::v('google_captcha_lang');
}
| Base | 1 |
foreach ($nodes as $node) {
if ((($perm == 'view' && $node->public == 1) || expPermissions::check($perm, expCore::makeLocation('navigation', '', $node->id))) && !in_array($node->id, $ignore_ids)) {
if ($node->active == 1) {
$text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . $node->name;
} else {
$text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . '(' . $node->name . ')';
}
$ar[$node->id] = $text;
foreach (self::levelDropdownControlArray($node->id, $depth + 1, $ignore_ids, $full, $perm, $addstandalones, $addinternalalias) as $id => $text) {
$ar[$id] = $text;
}
}
}
| Base | 1 |
public function showImage(string $path)
{
$path = storage_path('uploads/images/' . $path);
if (!file_exists($path)) {
throw (new NotFoundException(trans('errors.image_not_found')))
->setSubtitle(trans('errors.image_not_found_subtitle'))
->setDetails(trans('errors.image_not_found_details'));
}
return response()->file($path);
} | Base | 1 |
public function authenticate(CakeRequest $request, CakeResponse $response)
{
return self::getUser($request);
} | Base | 1 |
$variable[$key] = self::filter($val);
}
} else {
// Prevent XSS abuse
$variable = preg_replace_callback('#</?([a-z]+)(\s.*)?/?>#i', function($matches) {
$tag = strtolower($matches[1]);
// Allowed tags
if (in_array($tag, array(
'b', 'strong', 'small', 'i', 'em', 'u', 's', 'sub', 'sup', 'a', 'button', 'img', 'br',
'font', 'span', 'blockquote', 'q', 'abbr', 'address', 'code', 'hr',
'audio', 'video', 'source', 'iframe',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'ul', 'ol', 'li', 'dl', 'dt', 'dd',
'div', 'p', 'var',
'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'colgroup', 'col',
'section', 'article', 'aside'))) {
return $matches[0];
} else if (in_array($tag, array('script', 'link'))) {
return '';
} else {
return htmlentities($matches[0]);
}
}, $variable);
}
return $variable;
}
/**
* Retrieves the HTTP Method used by the client.
*
* @return string Either GET|POST|PUT|DEL...
*/
public static function getMethod() {
return $_SERVER['REQUEST_METHOD'];
}
/**
* Checks that the $url matches current route.
*
* @param string $url
* @param string $method (default = 'POST')
* @return bool
*/
public static function hasDataForURL($url, $method = 'POST') {
$route = WRoute::parseURL($url);
$current_route = WRoute::route();
return self::getMethod() == strtoupper($method)
&& $route['app'] == $current_route['app']
&& (!isset($current_route['params'][0]) || !isset($route['params'][0]) || $current_route['params'][0] == $route['params'][0]);
}
}
?>
| Base | 1 |
public function clearTags() {
$this->_tags = array(); // clear tag cache
return (bool) CActiveRecord::model('Tags')->deleteAllByAttributes(array(
'type' => get_class($this->getOwner()),
'itemId' => $this->getOwner()->id)
);
} | Class | 2 |
private function curl($url){
$ca = curl_init();
curl_setopt($ca, CURLOPT_URL, $url);
curl_setopt($ca, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ca, CURLOPT_HEADER, FALSE);
curl_setopt($ca, CURLOPT_HTTPHEADER, array("Accept: application/json"));
$response = curl_exec($ca);
curl_close($ca);
//var_dump($response);
$result = json_decode($response, true);
return $result;
}
| Base | 1 |
public function testXForwarderForHeaderForPassRequests()
{
$this->setNextResponse();
$server = array('REMOTE_ADDR' => '10.0.0.1');
$this->request('POST', '/', $server);
$this->assertEquals('10.0.0.1', $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For'));
} | Class | 2 |
function RegistrationSaveContactNameFields( $config, $values )
{
if ( empty( $values['FIRST_NAME'] )
|| empty( $values['LAST_NAME'] ) )
{
return 0;
}
$person_id = DBSeqNextID( 'people_person_id_seq' );
$sql = "INSERT INTO PEOPLE ";
$fields = 'PERSON_ID,LAST_NAME,FIRST_NAME,MIDDLE_NAME,';
$values_sql = "'" . $person_id . "','" . $values['LAST_NAME'] . "','" . $values['FIRST_NAME'] . "','" . $values['MIDDLE_NAME'] . "',";
if ( $config
&& ! empty( $values['fields'] ) )
{
foreach ( (array) $values['fields'] as $column => $value )
{
if ( is_array( $value ) )
{
// Select Multiple from Options field type format.
$value = implode( '||', $value ) ? '||' . implode( '||', $value ) : '';
}
if ( ! empty( $value )
|| $value == '0' )
{
$fields .= $column . ',';
$values_sql .= "'" . $value . "',";
}
}
}
$sql .= '(' . mb_substr( $fields, 0, -1 ) . ') values(' . mb_substr( $values_sql, 0, -1 ) . ')';
DBQuery( $sql );
return $person_id;
} | Base | 1 |
public function index() {
System::gZip();
Control::handler('frontend');
System::Zipped();
}
| Base | 1 |
$iloc = expUnserialize($container->internal);
if ($db->selectObject('sectionref',"module='".$iloc->mod."' AND source='".$iloc->src."'") == null) {
// There is no sectionref for this container. Populate sectionref
if ($container->external != "N;") {
$newSecRef = new stdClass();
$newSecRef->module = $iloc->mod;
$newSecRef->source = $iloc->src;
$newSecRef->internal = '';
$newSecRef->refcount = 1;
// $newSecRef->is_original = 1;
$eloc = expUnserialize($container->external);
// $section = $db->selectObject('sectionref',"module='containermodule' AND source='".$eloc->src."'");
$section = $db->selectObject('sectionref',"module='container' AND source='".$eloc->src."'");
if (!empty($section)) {
$newSecRef->section = $section->id;
$db->insertObject($newSecRef,"sectionref");
$missing_sectionrefs[] = gt("Missing sectionref for container replaced").": ".$iloc->mod." - ".$iloc->src." - PageID #".$section->id;
} else {
$db->delete('container','id="'.$container->id.'"');
$missing_sectionrefs[] = gt("Cant' find the container page for container").": ".$iloc->mod." - ".$iloc->src.' - '.gt('deleted');
}
}
}
}
assign_to_template(array(
'missing_sectionrefs'=>$missing_sectionrefs,
));
} | 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;
} | Base | 1 |
private function getCategory()
{
$category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));
if (empty($category)) {
throw new PageNotFoundException();
}
return $category;
} | Base | 1 |
public function getPurchaseOrderByJSON() {
if(!empty($this->params['vendor'])) {
$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);
} else {
$purchase_orders = $this->purchase_order->find('all');
}
echo json_encode($purchase_orders);
} | Class | 2 |
private function SearchFileContents()
{
$args = array();
$args[] = '-I';
$args[] = '--full-name';
$args[] = '--ignore-case';
$args[] = '-n';
$args[] = '-e';
$args[] = '"' . addslashes($this->search) . '"';
$args[] = $this->treeHash;
$lines = explode("\n", $this->exe->Execute($this->project->GetPath(), GIT_GREP, $args));
foreach ($lines as $line) {
if (preg_match('/^[^:]+:([^:]+):([0-9]+):(.+)$/', $line, $regs)) {
if (isset($this->allResults[$regs[1]])) {
$result = $this->allResults[$regs[1]];
$matchingLines = $result->GetMatchingLines();
$matchingLines[(int)($regs[2])] = trim($regs[3], "\n\r\0\x0B");
$result->SetMatchingLines($matchingLines);
} else {
$tree = $this->GetTree();
$hash = $tree->PathToHash($regs[1]);
if ($hash) {
$blob = $this->project->GetObjectManager()->GetBlob($hash);
$blob->SetPath($regs[1]);
$result = new GitPHP_FileSearchResult($this->project, $blob, $regs[1]);
$matchingLines = array();
$matchingLines[(int)($regs[2])] = trim($regs[3], "\n\r\0\x0B");
$result->SetMatchingLines($matchingLines);
$this->allResults[$regs[1]] = $result;
}
}
}
}
} | Base | 1 |
$cfgSite->setSetting( 'db', $key, $value);
}
$cfgSite->setSetting( 'site', 'secrethash', substr(md5(time() . ":" . mt_rand()),0,10));
return true;
} else {
return $Errors;
}
} | Base | 1 |
$params = ['uitype' => 71, 'displaytype' => 1, 'typeofdata' => 'N~O', 'isEditableReadOnly' => false, 'maximumlength' => '99999999999999999']; | Class | 2 |
public function update() {
global $user;
if (expSession::get('customer-signup')) expSession::set('customer-signup', false);
if (isset($this->params['address_country_id'])) {
$this->params['country'] = $this->params['address_country_id'];
unset($this->params['address_country_id']);
}
if (isset($this->params['address_region_id'])) {
$this->params['state'] = $this->params['address_region_id'];
unset($this->params['address_region_id']);
}
if ($user->isLoggedIn()) {
// check to see how many other addresses this user has already.
$count = $this->address->find('count', 'user_id='.$user->id);
// if this is first address save for this user we'll make this the default
if ($count == 0)
{
$this->params['is_default'] = 1;
$this->params['is_billing'] = 1;
$this->params['is_shipping'] = 1;
}
// associate this address with the current user.
$this->params['user_id'] = $user->id;
// save the object
$this->address->update($this->params);
}
else { //if (ecomconfig::getConfig('allow_anonymous_checkout')){
//user is not logged in, but allow anonymous checkout is enabled so we'll check
//a few things that we don't check in the parent 'stuff and create a user account.
$this->params['is_default'] = 1;
$this->params['is_billing'] = 1;
$this->params['is_shipping'] = 1;
$this->address->update($this->params);
}
expHistory::back();
} | Base | 1 |
function function_exists($name)
{
if (isset(\yiiunit\framework\base\SecurityTest::$functions[$name])) {
return \yiiunit\framework\base\SecurityTest::$functions[$name];
}
return \function_exists($name);
} | Class | 2 |
function set_menu_tabs()
{
$this->menu_tabs = array(
'tab1' => __('Ban Users', 'all-in-one-wp-security-and-firewall'),
);
}
| Base | 1 |
public function searchAdmin(){
$criteria = new CDbCriteria;
return $this->searchBase($criteria);
} | Class | 2 |
public function updateInfo(){
$user = $this->checkLogin();
$uid = $user['uid'];
$name = I("name");
D("User")->where(" uid = '$uid' ")->save(array("name"=>$name));
$this->sendResult(array());
} | Compound | 4 |
private function _addlasteditor( $option ) {
//Addlasteditor can not be used with addauthor.
if ( !isset( $this->parametersProcessed['addauthor'] ) || !$this->parametersProcessed['addauthor'] ) {
$this->addTable( 'revision_actor_temp', 'rev' );
$this->addWhere(
[
$this->tableNames['page'] . '.page_id = rev.revactor_page',
'rev.revactor_timestamp = (SELECT MAX(rev_aux_max.revactor_timestamp) FROM ' . $this->tableNames['revision_actor_temp'] . ' AS rev_aux_max WHERE rev_aux_max.revactor_page = rev.revactor_page)'
]
);
$this->_adduser( null, 'rev' );
}
} | Class | 2 |
$_fn[] = self::buildCondition($v, ' && ');
}
$fn[] = '('.\implode(' || ', $_fn).')';
break;
case '$where':
if (\is_callable($value)) {
// need implementation
}
break;
default:
$d = '$document';
if (\strpos($key, '.') !== false) {
$keys = \explode('.', $key);
foreach ($keys as $k) {
$d .= '[\''.$k.'\']';
}
} else {
$d .= '[\''.$key.'\']';
}
if (\is_array($value)) {
$fn[] = "\\MongoLite\\UtilArrayQuery::check((isset({$d}) ? {$d} : null), ".\var_export($value, true).')';
} else {
if (is_null($value)) {
$fn[] = "(!isset({$d}))";
} else {
$_value = \var_export($value, true);
$fn[] = "(isset({$d}) && (
is_array({$d}) && is_string({$_value})
? in_array({$_value}, {$d})
: {$d}=={$_value}
)
)";
}
}
}
}
return \count($fn) ? \trim(\implode($concat, $fn)) : 'true';
} | Base | 1 |
$navs[$i]->link = expCore::makeLink(array('section' => $navs[$i]->id), '', $navs[$i]->sef_name);
if (!$view) {
// unset($navs[$i]); //FIXME this breaks jstree if we remove a parent and not the child
$attr = new stdClass();
$attr->class = 'hidden'; // bs3 class to hide elements
$navs[$i]->li_attr = $attr;
}
}
| Class | 2 |
public static function dropdown($vars){
if(is_array($vars)){
//print_r($vars);
$name = $vars['name'];
$where = "WHERE `status` = '1' AND ";
if(isset($vars['type'])) {
$where .= " `type` = '{$vars['type']}' AND ";
}else{
$where .= " ";
}
$where .= " `status` = '1' ";
$order_by = "ORDER BY ";
if(isset($vars['order_by'])) {
$order_by .= " {$vars['order_by']} ";
}else{
$order_by .= " `name` ";
}
if (isset($vars['sort'])) {
$sort = " {$vars['sort']}";
}else{
$sort = 'ASC';
}
}
$cat = Db::result("SELECT * FROM `posts` {$where} {$order_by} {$sort}");
$num = Db::$num_rows;
$drop = "<select name=\"{$name}\" class=\"form-control\"><option></option>";
if($num > 0){
foreach ($cat as $c) {
# code...
// if($c->parent == ''){
if(isset($vars['selected']) && $c->id == $vars['selected']) $sel = "SELECTED"; else $sel = "";
$drop .= "<option value=\"{$c->id}\" $sel style=\"padding-left: 10px;\">{$c->title}</option>";
// foreach ($cat as $c2) {
// # code...
// if($c2->parent == $c->id){
// if(isset($vars['selected']) && $c2->id == $vars['selected']) $sel = "SELECTED"; else $sel = "";
// $drop .= "<option value=\"{$c2->id}\" $sel style=\"padding-left: 10px;\"> {$c2->name}</option>";
// }
// }
// }
}
}
$drop .= "</select>";
return $drop;
}
| Base | 1 |
public static function parseAndTrimExport($str, $isHTML = false) { //�Death from above�? �
//echo "1<br>"; eDebug($str);
$str = str_replace("�", "’", $str);
$str = str_replace("�", "‘", $str);
$str = str_replace("�", "®", $str);
$str = str_replace("�", "-", $str);
$str = str_replace("�", "—", $str);
$str = str_replace("�", "”", $str);
$str = str_replace("�", "“", $str);
$str = str_replace("\r\n", " ", $str);
$str = str_replace("\t", " ", $str);
$str = str_replace(",", "\,", $str);
$str = str_replace("�", "¼", $str);
$str = str_replace("�", "½", $str);
$str = str_replace("�", "¾", $str);
if (!$isHTML) {
$str = str_replace('\"', """, $str);
$str = str_replace('"', """, $str);
} else {
$str = str_replace('"', '""', $str);
}
//$str = htmlspecialchars($str);
//$str = utf8_encode($str);
$str = trim(str_replace("�", "™", $str));
//echo "2<br>"; eDebug($str,die);
return $str;
} | Class | 2 |
$sloc = expCore::makeLocation('navigation', null, $section->id);
// remove any manage permissions for this page and it's children
// $db->delete('userpermission', "module='navigationController' AND internal=".$section->id);
// $db->delete('grouppermission', "module='navigationController' AND internal=".$section->id);
foreach ($allusers as $uid) {
$u = user::getUserById($uid);
expPermissions::grant($u, 'manage', $sloc);
}
foreach ($allgroups as $gid) {
$g = group::getGroupById($gid);
expPermissions::grantGroup($g, 'manage', $sloc);
}
}
}
| 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 |
function update_option_master() {
global $db;
$id = empty($this->params['id']) ? null : $this->params['id'];
$opt = new option_master($id);
$oldtitle = $opt->title;
$opt->update($this->params);
// if the title of the master changed we should update the option groups that are already using it.
if ($oldtitle != $opt->title) {
}$db->sql('UPDATE '.$db->prefix.'option SET title="'.$opt->title.'" WHERE option_master_id='.$opt->id);
expHistory::back();
} | 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 ($week as $dayNum => $day) {
if ($dayNum == $now['mday']) {
$currentweek = $weekNum;
}
if ($dayNum <= $endofmonth) {
// $monthly[$weekNum][$dayNum]['number'] = ($monthly[$weekNum][$dayNum]['ts'] != -1) ? $db->countObjects("eventdate", $locsql . " AND date >= " . expDateTime::startOfDayTimestamp($day['ts']) . " AND date <= " . expDateTime::endOfDayTimestamp($day['ts'])) : -1;
$monthly[$weekNum][$dayNum]['number'] = ($monthly[$weekNum][$dayNum]['ts'] != -1) ? $ed->find("count", $locsql . " AND date >= " . expDateTime::startOfDayTimestamp($day['ts']) . " AND date <= " . expDateTime::endOfDayTimestamp($day['ts'])) : -1;
}
}
| Base | 1 |
private function getCategory()
{
$category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));
if (empty($category)) {
throw new PageNotFoundException();
}
return $category;
} | Base | 1 |
function test_new_comment_duplicated() {
$comment_args = array(
1,
'administrator',
'administrator',
self::$post->ID,
array(
'content' => rand_str( 100 ),
),
);
// First time it's a valid comment.
$result = $this->myxmlrpcserver->wp_newComment( $comment_args );
$this->assertNotIXRError( $result );
// Run second time for duplication error.
$result = $this->myxmlrpcserver->wp_newComment( $comment_args );
$this->assertIXRError( $result );
$this->assertSame( 403, $result->code );
} | Class | 2 |
public function update($id, $label, $extra)
{
$ret = $this->get($id);
if (!$ret) {
/* get() already logged and set $this->error. */
return self::ID_NOT_EXITS;
}
$class = get_class($this);
try {
$oldlabel = $ret->{$this->flabel};
$this->zdb->connection->beginTransaction();
$values = array(
$this->flabel => $label,
$this->fthird => $extra
);
$update = $this->zdb->update($this->table);
$update->set($values);
$update->where($this->fpk . ' = ' . $id);
$ret = $this->zdb->execute($update);
if ($oldlabel != $label) {
$this->deleteTranslation($oldlabel);
$this->addTranslation($label);
}
Analog::log(
$this->getType() . ' #' . $id . ' updated successfully.',
Analog::INFO
);
$this->zdb->connection->commit();
return true;
} catch (Throwable $e) {
$this->zdb->connection->rollBack();
Analog::log(
'Unable to update ' . $this->getType() . ' #' . $id . ' | ' .
$e->getMessage(),
Analog::ERROR
);
throw $e;
}
} | Base | 1 |
public static function exist($tag) {
$sql = "SELECT `name` FROM `cat` WHERE `name` = '{$tag}'";
$q = Db::result($sql);
if (Db::$num_rows > 0) {
return true;
}else{
return false;
}
}
| Base | 1 |
public function update_version() {
// get the current version
$hv = new help_version();
$current_version = $hv->find('first', 'is_current=1');
// check to see if the we have a new current version and unset the old current version.
if (!empty($this->params['is_current'])) {
// $db->sql('UPDATE '.DB_TABLE_PREFIX.'_help_version set is_current=0');
help_version::clearHelpVersion();
}
expSession::un_set('help-version');
// save the version
$id = empty($this->params['id']) ? null : $this->params['id'];
$version = new help_version();
// if we don't have a current version yet so we will force this one to be it
if (empty($current_version->id)) $this->params['is_current'] = 1;
$version->update($this->params);
// if this is a new version we need to copy over docs
if (empty($id)) {
self::copydocs($current_version->id, $version->id);
}
// let's update the search index to reflect the current help version
searchController::spider();
flash('message', gt('Saved help version').' '.$version->version);
expHistory::back();
} | Base | 1 |
function manage() {
global $db;
expHistory::set('manageable', $this->params);
// $classes = array();
$dir = BASE."framework/modules/ecommerce/billingcalculators";
if (is_readable($dir)) {
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
if (is_file("$dir/$file") && substr("$dir/$file", -4) == ".php") {
include_once("$dir/$file");
$classname = substr($file, 0, -4);
$id = $db->selectValue('billingcalculator', 'id', 'calculator_name="'.$classname.'"');
if (empty($id)) {
// $calobj = null;
$calcobj = new $classname();
if ($calcobj->isSelectable() == true) {
$obj = new billingcalculator(array(
'title'=>$calcobj->name(),
// 'user_title'=>$calcobj->title,
'body'=>$calcobj->description(),
'calculator_name'=>$classname,
'enabled'=>false));
$obj->save();
}
}
}
}
}
$bcalc = new billingcalculator();
$calculators = $bcalc->find('all');
assign_to_template(array(
'calculators'=>$calculators
));
} | Class | 2 |
foreach ( $metric_group_members as $index => $metric_name ) {
print "
<A HREF=\"./graph_all_periods.php?mobile=1&" . $g_metrics[$metric_name]['graph'] . "\">
<IMG BORDER=0 ALT=\"$clustername\" SRC=\"./graph.php?" . $g_metrics[$metric_name]['graph'] . "\"></A>";
} | 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 |
public static function dplNumParserFunction( &$parser, $text = '' ) {
$parser->addTrackingCategory( 'dplnum-parserfunc-tracking-category' );
$num = str_replace( ' ', ' ', $text );
$num = str_replace( ' ', ' ', $text );
$num = preg_replace( '/([0-9])([.])([0-9][0-9]?[^0-9,])/', '\1,\3', $num );
$num = preg_replace( '/([0-9.]+),([0-9][0-9][0-9])\s*Mrd/', '\1\2 000000 ', $num );
$num = preg_replace( '/([0-9.]+),([0-9][0-9])\s*Mrd/', '\1\2 0000000 ', $num );
$num = preg_replace( '/([0-9.]+),([0-9])\s*Mrd/', '\1\2 00000000 ', $num );
$num = preg_replace( '/\s*Mrd/', '000000000 ', $num );
$num = preg_replace( '/([0-9.]+),([0-9][0-9][0-9])\s*Mio/', '\1\2 000 ', $num );
$num = preg_replace( '/([0-9.]+),([0-9][0-9])\s*Mio/', '\1\2 0000 ', $num );
$num = preg_replace( '/([0-9.]+),([0-9])\s*Mio/', '\1\2 00000 ', $num );
$num = preg_replace( '/\s*Mio/', '000000 ', $num );
$num = preg_replace( '/[. ]/', '', $num );
$num = preg_replace( '/^[^0-9]+/', '', $num );
$num = preg_replace( '/[^0-9].*/', '', $num );
return $num;
} | Class | 2 |
public static function options($var) {
$file = GX_MOD.$var.'/options.php';
if(file_exists($file)){
include ($file);
}
}
| Base | 1 |
public function isAllowedFilename($filename){
$allow_array = array(
'.jpg','.jpeg','.png','.bmp','.gif','.ico','.webp',
'.mp3','.wav','.mp4',
'.mov','.webmv','.flac','.mkv',
'.zip','.tar','.gz','.tgz','.ipa','.apk','.rar','.iso',
'.pdf','.ofd','.swf','.epub','.xps',
'.doc','.docx','.wps',
'.ppt','.pptx','.xls','.xlsx','.txt','.psd','.csv',
'.cer','.ppt','.pub','.json','.css',
) ;
$ext = strtolower(substr($filename,strripos($filename,'.')) ); //获取文件扩展名(转为小写后)
if(in_array( $ext , $allow_array ) ){
return true ;
}
return false;
} | Base | 1 |
function db_case($array)
{
global $DatabaseType;
$counter = 0;
if ($DatabaseType == 'mysqli') {
$array_count = count($array);
$string = " CASE WHEN $array[0] =";
$counter++;
$arr_count = count($array);
for ($i = 1; $i < $arr_count; $i++) {
$value = $array[$i];
if ($value == "''" && substr($string, -1) == '=') {
$value = ' IS NULL';
$string = substr($string, 0, -1);
}
$string .= "$value";
if ($counter == ($array_count - 2) && $array_count % 2 == 0)
$string .= " ELSE ";
elseif ($counter == ($array_count - 1))
$string .= " END ";
elseif ($counter % 2 == 0)
$string .= " WHEN $array[0]=";
elseif ($counter % 2 == 1)
$string .= " THEN ";
$counter++;
}
}
return $string;
} | Base | 1 |
$count += $db->dropTable($basename);
}
flash('message', gt('Deleted').' '.$count.' '.gt('unused tables').'.');
expHistory::back();
} | Base | 1 |
private function SendHello($hello, $host) {
fputs($this->smtp_conn, $hello . " " . $host . $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" => $hello . " not accepted from server",
"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;
}
$this->helo_rply = $rply;
return true;
} | Base | 1 |
protected function getComment()
{
$comment = $this->commentModel->getById($this->request->getIntegerParam('comment_id'));
if (empty($comment)) {
throw new PageNotFoundException();
}
if (! $this->userSession->isAdmin() && $comment['user_id'] != $this->userSession->getId()) {
throw new AccessForbiddenException();
}
return $comment;
} | Base | 1 |
public function remove()
{
$this->checkCSRFParam();
$project = $this->getProject();
$category = $this->getCategory();
if ($this->categoryModel->remove($category['id'])) {
$this->flash->success(t('Category removed successfully.'));
} else {
$this->flash->failure(t('Unable to remove this category.'));
}
$this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])));
} | Base | 1 |
private function getCategory()
{
$category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));
if (empty($category)) {
throw new PageNotFoundException();
}
return $category;
} | Base | 1 |
protected function redirectToOperator(Thread $thread, $operator_id)
{
if ($thread->state != Thread::STATE_CHATTING) {
// We can redirect only threads which are in proggress now.
return false;
}
// Redirect the thread
$thread->state = Thread::STATE_WAITING;
$thread->nextAgent = $operator_id;
$thread->agentId = 0;
// Check if the target operator belongs to the current thread's group.
// If not reset the current thread's group.
if ($thread->groupId != 0) {
$db = Database::getInstance();
list($groups_count) = $db->query(
("SELECT count(*) AS count "
. "FROM {operatortoopgroup} "
. "WHERE operatorid = ? AND groupid = ?"),
array($operator_id, $thread->groupId),
array(
'return_rows' => Database::RETURN_ONE_ROW,
'fetch_type' => Database::FETCH_NUM,
)
);
if ($groups_count === 0) {
$thread->groupId = 0;
}
}
$thread->save();
// Send notification message
$thread->postMessage(
Thread::KIND_EVENTS,
getlocal(
'Operator {0} redirected you to another operator. Please wait a while.',
array(get_operator_name($this->getOperator())),
$thread->locale,
true
)
);
return true;
} | Base | 1 |
static function displayname() { return gt("Navigation"); }
| 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 |
protected function _mkfile($path, $name) {
$path = $this->_joinPath($path, $name);
if (($fp = @fopen($path, 'w'))) {
@fclose($fp);
@chmod($path, $this->options['fileMode']);
clearstatcache();
return $path;
}
return false;
} | Base | 1 |
public function store($zdb)
{
$data = array(
'short_label' => $this->short,
'long_label' => $this->long
);
try {
if ($this->id !== null && $this->id > 0) {
$update = $zdb->update(self::TABLE);
$update->set($data)->where([self::PK => $this->id]);
$zdb->execute($update);
} else {
$insert = $zdb->insert(self::TABLE);
$insert->values($data);
$add = $zdb->execute($insert);
if (!$add->count() > 0) {
Analog::log('Not stored!', Analog::ERROR);
return false;
}
$this->id = $zdb->getLastGeneratedValue($this);
}
return true;
} catch (Throwable $e) {
Analog::log(
'An error occurred storing title: ' . $e->getMessage() .
"\n" . print_r($data, true),
Analog::ERROR
);
throw $e;
}
} | Base | 1 |
public function testGetDropdownValue($params, $expected, $session_params = []) {
$this->login();
$bkp_params = [];
//set session params if any
if (count($session_params)) {
foreach ($session_params as $param => $value) {
if (isset($_SESSION[$param])) {
$bkp_params[$param] = $_SESSION[$param];
}
$_SESSION[$param] = $value;
}
}
$params['_idor_token'] = \Session::getNewIDORToken($params['itemtype'] ?? '');
$result = \Dropdown::getDropdownValue($params, false);
//reset session params before executing test
if (count($session_params)) {
foreach ($session_params as $param => $value) {
if (isset($bkp_params[$param])) {
$_SESSION[$param] = $bkp_params[$param];
} else {
unset($_SESSION[$param]);
}
}
}
$this->array($result)->isIdenticalTo($expected);
} | Class | 2 |
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,
)));
} | Class | 2 |
public function approve_toggle() {
global $history;
if (empty($this->params['id'])) return;
/* 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']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];
$require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];
$require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];
$notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];
$simplenote = new expSimpleNote($this->params['id']);
$simplenote->approved = $simplenote->approved == 1 ? 0 : 1;
$simplenote->save();
$lastUrl = makelink($history->history[$history->history['lasts']['type']][count($history->history[$history->history['lasts']['type']])-1]['params']);
if (!empty($this->params['tab']))
{
$lastUrl .= "#".$this->params['tab'];
}
redirect_to($lastUrl);
} | Base | 1 |
public function isActive()
{
if (PHP_VERSION_ID >= 50400) {
return $this->active = \PHP_SESSION_ACTIVE === session_status();
}
return $this->active;
} | Base | 1 |
function __construct() {
}
| 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;
} | Compound | 4 |
protected function _move($source, $targetDir, $name)
{
$target = $this->_joinPath($targetDir, $name);
return $this->connect->rename($source, $target) ? $target : false;
} | Base | 1 |
$res = preg_match("/^$map_part/", $this->url_parts[$i]);
if ($res != 1) {
$matched = false;
break;
}
$pairs[$key] = $this->url_parts[$i];
$i++;
}
} else {
$matched = false;
}
if ($matched) {
// safeguard against false matches when a real action was what the user really wanted.
if (count($this->url_parts) >= 2 && method_exists(expModules::getController($this->url_parts[0]), $this->url_parts[1]))
return false;
$this->url_parts = array();
$this->url_parts[0] = $map['controller'];
$this->url_parts[1] = $map['action'];
if (isset($map['view'])) {
$this->url_parts[2] = 'view';
$this->url_parts[3] = $map['view'];
}
foreach($map as $key=>$value) {
if ($key != 'controller' && $key != 'action' && $key != 'view' && $key != 'url_parts') {
$this->url_parts[] = $key;
$this->url_parts[] = $value;
}
}
foreach($pairs as $key=>$value) {
if ($key != 'controller') {
$this->url_parts[] = $key;
$this->url_parts[] = $value;
}
}
$this->params = $this->convertPartsToParams();
return true;
}
}
return false;
} | Base | 1 |
private function encloseForCSV($field)
{
return '"' . cleanCSV($field) . '"';
} | Base | 1 |
function restart($sMessage = '')
{
$_COOKIE['sessionID'] = phpAds_SessionStart();
OA_Auth::displayLogin($sMessage, $_COOKIE['sessionID']);
} | Compound | 4 |
foreach ($week as $dayNum => $day) {
if ($dayNum == $now['mday']) {
$currentweek = $weekNum;
}
if ($dayNum <= $endofmonth) {
// $monthly[$weekNum][$dayNum]['number'] = ($monthly[$weekNum][$dayNum]['ts'] != -1) ? $db->countObjects("eventdate", $locsql . " AND date >= " . expDateTime::startOfDayTimestamp($day['ts']) . " AND date <= " . expDateTime::endOfDayTimestamp($day['ts'])) : -1;
$monthly[$weekNum][$dayNum]['number'] = ($monthly[$weekNum][$dayNum]['ts'] != -1) ? $ed->find("count", $locsql . " AND date >= " . expDateTime::startOfDayTimestamp($day['ts']) . " AND date <= " . expDateTime::endOfDayTimestamp($day['ts'])) : -1;
}
}
| Base | 1 |
function delete_recurring() {
$item = $this->event->find('first', 'id=' . $this->params['id']);
if ($item->is_recurring == 1) { // need to give user options
expHistory::set('editable', $this->params);
assign_to_template(array(
'checked_date' => $this->params['date_id'],
'event' => $item,
));
} else { // Process a regular delete
$item->delete();
}
}
| Base | 1 |
public function editAlt() {
global $user;
$file = new expFile($this->params['id']);
if ($user->id==$file->poster || $user->isAdmin()) {
$file->alt = $this->params['newValue'];
$file->save();
$ar = new expAjaxReply(200, gt('Your alt was updated successfully'), $file);
} else {
$ar = new expAjaxReply(300, gt("You didn't create this file, so you can't edit it."));
}
$ar->send();
echo json_encode($file); //FIXME we exit before hitting this
} | Base | 1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.