code
stringlengths 12
2.05k
| label_name
stringclasses 5
values | label
int64 0
4
|
---|---|---|
static public function compress_png($path, $max_quality = 85) {
$check = shell_exec("pngquant --version");
if(!$check) {
return false;
}else{
// guarantee that quality won't be worse than that.
$min_quality = 60;
// '-' makes it use stdout, required to save to $compressed_png_content variable
// '<' makes it read from the given file path
// escapeshellarg() makes this safe to use with any path
$compressed_png_content = shell_exec("pngquant --quality=$min_quality-$max_quality - < ".escapeshellarg($path));
if (!$compressed_png_content) {
throw new Exception("Conversion to compressed PNG failed. Is pngquant 1.8+ installed on the server?");
}else{
file_put_contents($path, $compressed_png_content);
return true;
}
}
}
| Base | 1 |
static function convertXMLFeedSafeChar($str) {
$str = str_replace("<br>","",$str);
$str = str_replace("</br>","",$str);
$str = str_replace("<br/>","",$str);
$str = str_replace("<br />","",$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("�", '"', $str);
$str = str_replace("”",'"', $str);
$str = str_replace("�", '"', $str);
$str = str_replace("“",'"', $str);
$str = str_replace("\r\n"," ",$str);
$str = str_replace("�"," 1/4",$str);
$str = str_replace("¼"," 1/4", $str);
$str = str_replace("�"," 1/2",$str);
$str = str_replace("½"," 1/2",$str);
$str = str_replace("�"," 3/4",$str);
$str = str_replace("¾"," 3/4",$str);
$str = str_replace("�", "(TM)", $str);
$str = str_replace("™","(TM)", $str);
$str = str_replace("®","(R)", $str);
$str = str_replace("�","(R)",$str);
$str = str_replace("&","&",$str);
$str = str_replace(">",">",$str);
return trim($str);
} | Base | 1 |
protected function assertNoPHPErrors () {
$this->assertElementNotPresent('css=.xdebug-error');
$this->assertElementNotPresent('css=#x2-php-error');
} | Base | 1 |
public function getRequestTarget()
{
if ($this->requestTarget !== null) {
return $this->requestTarget;
}
$target = $this->uri->getPath();
if ($target == null) {
$target = '/';
}
if ($this->uri->getQuery()) {
$target .= '?' . $this->uri->getQuery();
}
return $target;
} | 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 |
public function addCC($address, $name = '')
{
return $this->addAnAddress('cc', $address, $name);
} | Compound | 4 |
public function approve_toggle() {
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']) ? 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->approved = $comment->approved == 1 ? 0 : 1;
if ($comment->approved) {
$this->sendApprovalNotification($comment,$this->params);
}
$comment->save();
expHistory::back();
} | Class | 2 |
public static function remove_properties($element_type, $element_id, $website_id)
{
global $DB;
global $website;
if(empty($website_id))
$website_id = $website->id;
webdictionary::save_element_strings('property-'.$element_type, $element_id, array());
$DB->execute('
DELETE FROM nv_properties_items
WHERE website = '.$website_id.'
AND element = '.protect($element_type).'
AND node_id = '.intval($element_id).'
');
}
| Base | 1 |
function lockTable($table,$lockType="WRITE") {
$sql = "LOCK TABLES `" . $this->prefix . "$table` $lockType";
$res = mysqli_query($this->connection, $sql);
return $res;
} | Base | 1 |
function delete_selected() {
$item = $this->event->find('first', 'id=' . $this->params['id']);
if ($item && $item->is_recurring == 1) {
$event_remaining = false;
$eventdates = $item->eventdate[0]->find('all', 'event_id=' . $item->id);
foreach ($eventdates as $ed) {
if (array_key_exists($ed->id, $this->params['dates'])) {
$ed->delete();
} else {
$event_remaining = true;
}
}
if (!$event_remaining) {
$item->delete(); // model will also ensure we delete all event dates
}
expHistory::back();
} else {
notfoundController::handle_not_found();
}
}
| Base | 1 |
$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 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 |
public function view() {
$params = func_get_args();
$content = '';
$filename = urldecode(join('/', $params));
// Sanitize filename for securtiy
// We don't allow backlinks
if (strpos($filename, '..') !== false) {
/*
if (Plugin::isEnabled('statistics_api')) {
$user = null;
if (AuthUser::isLoggedIn())
$user = AuthUser::getUserName();
$ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : ($_SERVER['REMOTE_ADDR']);
$event = array('event_type' => 'hack_attempt', // simple event type identifier
'description' => __('A possible hack attempt was detected.'), // translatable description
'ipaddress' => $ip,
'username' => $user);
Observer::notify('stats_file_manager_hack_attempt', $event);
}
*/
}
$filename = str_replace('..', '', $filename);
// Clean up nicely
$filename = str_replace('//', '', $filename);
// We don't allow leading slashes
$filename = preg_replace('/^\//', '', $filename);
// Check if file had URL_SUFFIX - if so, append it to filename
$filename .= (isset($_GET['has_url_suffix']) && $_GET['has_url_suffix']==='1') ? URL_SUFFIX : '';
$file = FILES_DIR . '/' . $filename;
if (!$this->_isImage($file) && file_exists($file)) {
$content = file_get_contents($file);
}
$this->display('file_manager/views/view', array(
'csrf_token' => SecureToken::generateToken(BASE_URL.'plugin/file_manager/save/'.$filename),
'is_image' => $this->_isImage($file),
'filename' => $filename,
'content' => $content
));
} | Class | 2 |
protected function optionsPage()
{
//FIXME Put Options code in here.
} | Base | 1 |
public function testAlwaysReturnsBody()
{
$r = new Response();
$this->assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
} | Base | 1 |
static function author() {
return "Dave Leffler";
}
| Base | 1 |
public static function loadonce($var){
require_once(GX_LIB."Vendor/".$var);
}
| Base | 1 |
static function description() {
return gt("This module is for managing categories in your store.");
} | Base | 1 |
$files[$key]->save();
}
// eDebug($files,true);
} | Class | 2 |
function checkOldRoutes($path) {
$found = false;
$x = count($path);
while ($x) {
$f = sqlfetch(sqlquery("SELECT * FROM bigtree_route_history WHERE old_route = '".implode("/",array_slice($path,0,$x))."'"));
if ($f) {
$old = $f["old_route"];
$new = $f["new_route"];
$found = true;
break;
}
$x--;
}
// If it's in the old routing table, send them to the new page.
if ($found) {
$new_url = $new.substr($_GET["bigtree_htaccess_url"],strlen($old));
BigTree::redirect(WWW_ROOT.$new_url,"301");
}
} | Base | 1 |
public function activate_discount(){
if (isset($this->params['id'])) {
$discount = new discounts($this->params['id']);
$discount->update($this->params);
//if ($discount->discountulator->hasConfig() && empty($discount->config)) {
//flash('messages', $discount->discountulator->name().' requires configuration. Please do so now.');
//redirect_to(array('controller'=>'billing', 'action'=>'configure', 'id'=>$discount->id));
//}
}
expHistory::back();
} | Base | 1 |
static function description() {
return gt("This module is for managing categories in your store.");
} | Base | 1 |
function article_save()
{
global $txp_user, $vars, $prefs;
extract($prefs);
$incoming = array_map('assert_string', psa($vars));
$oldArticle = safe_row('Status, url_title, Title, '.
'unix_timestamp(LastMod) as sLastMod, LastModID, '.
'unix_timestamp(Posted) as sPosted, '.
'unix_timestamp(Expires) as sExpires',
'textpattern', 'ID = '.(int) $incoming['ID']); | 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,
)));
} | Base | 1 |
$rst[$key] = self::parseAndTrim($st, $unescape);
}
return $rst;
}
$str = str_replace("<br>"," ",$str);
$str = str_replace("</br>"," ",$str);
$str = str_replace("<br/>"," ",$str);
$str = str_replace("<br />"," ",$str);
$str = str_replace("\r\n"," ",$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("”","”", $str);
$str = str_replace("“","“", $str);
$str = str_replace("¼","¼",$str);
$str = str_replace("½","½",$str);
$str = str_replace("¾","¾",$str);
$str = str_replace("™","™", $str);
$str = trim($str);
if ($unescape) {
$str = stripcslashes($str);
} else {
$str = addslashes($str);
}
return $str;
} | Base | 1 |
public function save()
{
global $DB;
if(!empty($this->id))
return $this->update();
else
return $this->insert();
}
| Base | 1 |
public function get_news_list($howmany) {
$sql = 'SELECT id, subject, body, postedby, UNIX_TIMESTAMP(postdate) AS postdate
FROM ' . TABLE_PREFIX .'news ORDER BY postdate DESC LIMIT '.$howmany;
return DB::get_results($sql);
} | Base | 1 |
static function convertUTF($string) {
return $string = str_replace('?', '', htmlspecialchars($string, ENT_IGNORE, 'UTF-8'));
} | Class | 2 |
public function Insert() {
$ins_stmt = Database::prepare("
INSERT INTO `" . TABLE_PANEL_TICKETS . "` SET
`customerid` = :customerid,
`adminid` = :adminid,
`category` = :category,
`priority` = :priority,
`subject` = :subject,
`message` = :message,
`dt` = :dt,
`lastchange` = :lastchange,
`ip` = :ip,
`status` = :status,
`lastreplier` = :lastreplier,
`by` = :by,
`answerto` = :answerto"
);
$ins_data = array(
'customerid' => $this->Get('customer'),
'adminid' => $this->Get('admin'),
'category' => $this->Get('category'),
'priority' => $this->Get('priority'),
'subject' => $this->Get('subject'),
'message' => $this->Get('message'),
'dt' => time(),
'lastchange' => time(),
'ip' => $this->Get('ip'),
'status' => $this->Get('status'),
'lastreplier' => $this->Get('lastreplier'),
'by' => $this->Get('by'),
'answerto' => $this->Get('answerto')
);
Database::pexecute($ins_stmt, $ins_data);
$this->tid = Database::lastInsertId();
return true;
} | Class | 2 |
public function manage_versions() {
expHistory::set('manageable', $this->params);
$hv = new help_version();
$current_version = $hv->find('first', 'is_current=1');
$sql = 'SELECT hv.*, COUNT(h.title) AS num_docs FROM '.DB_TABLE_PREFIX.'_help h ';
$sql .= 'RIGHT JOIN '.DB_TABLE_PREFIX.'_help_version hv ON h.help_version_id=hv.id GROUP BY hv.version';
$page = new expPaginator(array(
'sql'=>$sql,
'limit'=>30,
'order' => (isset($this->params['order']) ? $this->params['order'] : 'version'),
'dir' => (isset($this->params['dir']) ? $this->params['dir'] : 'DESC'),
'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
'controller'=>$this->baseclassname,
'action'=>$this->params['action'],
'src'=>$this->loc->src,
'columns'=>array(
gt('Version')=>'version',
gt('Title')=>'title',
gt('Current')=>'is_current',
gt('# of Docs')=>'num_docs'
),
));
assign_to_template(array(
'current_version'=>$current_version,
'page'=>$page
));
} | Base | 1 |
public function download($name){
$attachFile = storage_path('app/'.str_replace("-","/",$name));
if(!is_file($attachFile)){
abort(404);
}
return response()->download($attachFile);
} | 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 |
public function __construct($strSystemid = "") {
//Generating all the required objects. For this we use our cool cool carrier-object
//take care of loading just the necessary objects
$objCarrier = class_carrier::getInstance();
$this->objConfig = $objCarrier->getObjConfig();
$this->objSession = $objCarrier->getObjSession();
$this->objLang = $objCarrier->getObjLang();
$this->objTemplate = $objCarrier->getObjTemplate();
//Setting SystemID
if($strSystemid == "") {
$this->setSystemid(class_carrier::getInstance()->getParam("systemid"));
}
else {
$this->setSystemid($strSystemid);
}
//And keep the action
$this->strAction = $this->getParam("action");
//in most cases, the list is the default action if no other action was passed
if($this->strAction == "") {
$this->strAction = "list";
}
//try to load the current module-name and the moduleId by reflection
$objReflection = new class_reflection($this);
if(!isset($this->arrModule["modul"])) {
$arrAnnotationValues = $objReflection->getAnnotationValuesFromClass(self::STR_MODULE_ANNOTATION);
if(count($arrAnnotationValues) > 0)
$this->setArrModuleEntry("modul", trim($arrAnnotationValues[0]));
}
if(!isset($this->arrModule["moduleId"])) {
$arrAnnotationValues = $objReflection->getAnnotationValuesFromClass(self::STR_MODULEID_ANNOTATION);
if(count($arrAnnotationValues) > 0)
$this->setArrModuleEntry("moduleId", constant(trim($arrAnnotationValues[0])));
}
$this->strLangBase = $this->getArrModule("modul");
} | Base | 1 |
private function getResponse ($size = 128) {
$pop3_response = fgets($this->pop_conn, $size);
return $pop3_response;
} | Base | 1 |
public function confirm()
{
$project = $this->getProject();
$this->response->html($this->helper->layout->project('action/remove', array(
'action' => $this->actionModel->getById($this->request->getIntegerParam('action_id')),
'available_events' => $this->eventManager->getAll(),
'available_actions' => $this->actionManager->getAvailableActions(),
'project' => $project,
'title' => t('Remove an action')
)));
} | Base | 1 |
$db->updateObject($value, 'section');
}
$db->updateObject($moveSec, 'section');
//handle re-ranking of previous parent
$oldSiblings = $db->selectObjects("section", "parent=" . $oldParent . " AND rank>" . $oldRank . " ORDER BY rank");
$rerank = 1;
foreach ($oldSiblings as $value) {
if ($value->id != $moveSec->id) {
$value->rank = $rerank;
$db->updateObject($value, 'section');
$rerank++;
}
}
if ($oldParent != $moveSec->parent) {
//we need to re-rank the children of the parent that the moving section has just left
$childOfLastMove = $db->selectObjects("section", "parent=" . $oldParent . " ORDER BY rank");
for ($i = 0, $iMax = count($childOfLastMove); $i < $iMax; $i++) {
$childOfLastMove[$i]->rank = $i;
$db->updateObject($childOfLastMove[$i], 'section');
}
}
}
}
self::checkForSectionalAdmins($move);
expSession::clearAllUsersSessionCache('navigation');
}
| Class | 2 |
function rsvpmaker_relay_menu_pages() {
$parent_slug = 'edit.php?post_type=rsvpemail';
add_submenu_page(
$parent_slug,
__( 'Group Email', 'rsvpmaker' ),
__( 'Group Email', 'rsvpmaker' ),
'manage_options',
'rsvpmaker_relay_manual_test',
'rsvpmaker_relay_manual_test'
);
add_submenu_page(
$parent_slug,
__( 'Group Email Log', 'rsvpmaker' ),
__( 'Group Email Log', 'rsvpmaker' ),
'manage_options',
'rsvpmaker_relay_log',
'rsvpmaker_relay_log'
);
} | Base | 1 |
function delete_vendor() {
global $db;
if (!empty($this->params['id'])){
$db->delete('vendor', 'id =' .$this->params['id']);
}
expHistory::back();
} | Base | 1 |
public function theme_switch() {
if (!expUtil::isReallyWritable(BASE.'framework/conf/config.php')) { // we can't write to the config.php file
flash('error',gt('The file /framework/conf/config.php is NOT Writeable. You will be unable to change the theme.'));
}
expSettings::change('DISPLAY_THEME_REAL', $this->params['theme']);
expSession::set('display_theme',$this->params['theme']);
$sv = isset($this->params['sv'])?$this->params['sv']:'';
if (strtolower($sv)=='default') {
$sv = '';
}
expSettings::change('THEME_STYLE_REAL',$sv);
expSession::set('theme_style',$sv);
expDatabase::install_dbtables(); // update tables to include any custom definitions in the new theme
// $message = (MINIFY != 1) ? "Exponent is now minifying Javascript and CSS" : "Exponent is no longer minifying Javascript and CSS" ;
// flash('message',$message);
$message = gt("You have selected the")." '".$this->params['theme']."' ".gt("theme");
if ($sv != '') {
$message .= ' '.gt('with').' '.$this->params['sv'].' '.gt('style variation');
}
flash('message',$message);
// expSession::un_set('framework');
expSession::set('force_less_compile', 1);
// expTheme::removeSmartyCache();
expSession::clearAllUsersSessionCache();
expHistory::returnTo('manageable');
} | Base | 1 |
public function getModuleItemString() {
$ret = $this->handler->_moduleName . '_' . $this->handler->_itemname;
return $ret;
}
| Base | 1 |
function get(&$dbh, $proposalId, $handle)
{
$sql = "SELECT *, UNIX_TIMESTAMP(timestamp) AS timestamp FROM package_proposal_votes WHERE pkg_prop_id = ". $dbh->quoteSmart($proposalId) ." AND user_handle= ". $dbh->quoteSmart($handle);
$res = $dbh->query($sql);
if (DB::isError($res)) {
return $res;
}
if (!$res->numRows()) {
return null;
}
$set = $res->fetchRow(DB_FETCHMODE_ASSOC);
$set['reviews'] = unserialize($set['reviews']);
$vote = new ppVote($set);
return $vote;
} | Base | 1 |
function update_vendor() {
$vendor = new vendor();
$vendor->update($this->params['vendor']);
expHistory::back();
} | Class | 2 |
function update_upcharge() {
$this->loc->src = "@globalstoresettings";
$config = new expConfig($this->loc);
$this->config = $config->config;
//This will make sure that only the country or region that given a rate value will be saved in the db
$upcharge = array();
foreach($this->params['upcharge'] as $key => $item) {
if(!empty($item)) {
$upcharge[$key] = $item;
}
}
$this->config['upcharge'] = $upcharge;
$config->update(array('config'=>$this->config));
flash('message', gt('Configuration updated'));
expHistory::back();
} | Class | 2 |
public static function data($vars){
$file = GX_MOD.'/'.$vars.'/index.php';
$handle = fopen($file, 'r');
$data = fread($handle, filesize($file));
fclose($handle);
preg_match('/\* Name: (.*)\n\*/U', $data, $matches);
$d['name'] = $matches[1];
preg_match('/\* Desc: (.*)\n\*/U', $data, $matches);
$d['desc'] = $matches[1];
preg_match('/\* Version: (.*)\n\*/U', $data, $matches);
$d['version'] = $matches[1];
preg_match('/\* Build: (.*)\n\*/U', $data, $matches);
$d['build'] = $matches[1];
preg_match('/\* Developer: (.*)\n\*/U', $data, $matches);
$d['developer'] = $matches[1];
preg_match('/\* URI: (.*)\n\*/U', $data, $matches);
$d['url'] = $matches[1];
preg_match('/\* License: (.*)\n\*/U', $data, $matches);
$d['license'] = $matches[1];
preg_match('/\* Icon: (.*)\n\*/U', $data, $matches);
$d['icon'] = $matches[1];
return $d;
}
| 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 |
public function show()
{
$task = $this->getTask();
$subtask = $this->getSubtask();
$this->response->html($this->template->render('subtask_converter/show', array(
'subtask' => $subtask,
'task' => $task,
)));
} | Class | 2 |
public static function getId($id=''){
if(isset($id)){
$sql = sprintf("SELECT * FROM `menus` WHERE `id` = '%d' ORDER BY `order` ASC", $id);
$menus = Db::result($sql);
$n = Db::$num_rows;
}else{
$menus = '';
}
return $menus;
} | Base | 1 |
public static function page($vars) {
switch (SMART_URL) {
case true:
$inFold = (Options::v('permalink_use_index_php') == "on")? "/index.php/":"/";
if (Options::v('multilang_enable') === 'on') {
$lang = Language::isActive();
$lang = !empty($lang)? $lang . '/': '';
$url = Site::$url.$inFold. $lang .self::slug($vars).GX_URL_PREFIX;
}else{
$url = Site::$url.$inFold.self::slug($vars).GX_URL_PREFIX;
}
break;
default:
if (Options::v('multilang_enable') === 'on') {
$lang = Language::isActive();
$lang = !empty($lang)? '&lang=' . $lang: '';
$url = Site::$url."/?page={$vars}{$lang}";
}else{
$url = Site::$url."/?page={$vars}";
}
break;
}
return $url;
}
| Base | 1 |
public function testDecrypt($expected, $key, $string) {
$this->string(\Toolbox::decrypt($string, $key))->isIdenticalTo($expected);
} | Class | 2 |
public static function doTablesUpdate($definition){
$updateInformation = self::getTablesStatus($definition);
$db = ezcDbInstance::get();
$errorMessages = array();
try {
$db->query('SET GLOBAL innodb_strict_mode = 0;');
$db->query('SET GLOBAL innodb_file_per_table=1;');
$db->query('SET GLOBAL innodb_large_prefix=1;');
} catch (Exception $e) {
//$errorMessages[] = $e->getMessage();
}
foreach ($updateInformation as $table => $tableData) {
if ($tableData['error'] == true) {
foreach ($tableData['queries'] as $query) {
try {
$db->query($query);
} catch (Exception $e) {
$errorMessages[] = $e->getMessage();
}
}
}
}
return $errorMessages;
}
| Base | 1 |
static function displayname() {
return "Events";
}
| Base | 1 |
public function params()
{
$project = $this->getProject();
$values = $this->request->getValues();
if (empty($values['action_name']) || empty($values['project_id']) || empty($values['event_name'])) {
$this->create();
return;
}
$action = $this->actionManager->getAction($values['action_name']);
$action_params = $action->getActionRequiredParameters();
if (empty($action_params)) {
$this->doCreation($project, $values + array('params' => array()));
}
$projects_list = $this->projectUserRoleModel->getActiveProjectsByUser($this->userSession->getId());
unset($projects_list[$project['id']]);
$this->response->html($this->template->render('action_creation/params', array(
'values' => $values,
'action_params' => $action_params,
'columns_list' => $this->columnModel->getList($project['id']),
'users_list' => $this->projectUserRoleModel->getAssignableUsersList($project['id']),
'projects_list' => $projects_list,
'colors_list' => $this->colorModel->getList(),
'categories_list' => $this->categoryModel->getList($project['id']),
'links_list' => $this->linkModel->getList(0, false),
'priorities_list' => $this->projectTaskPriorityModel->getPriorities($project),
'project' => $project,
'available_actions' => $this->actionManager->getAvailableActions(),
'swimlane_list' => $this->swimlaneModel->getList($project['id']),
'events' => $this->actionManager->getCompatibleEvents($values['action_name']),
)));
} | 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 |
$this->subtaskTimeTrackingModel->logEndTime($subtaskId, $this->userSession->getId());
$this->subtaskTimeTrackingModel->updateTaskTimeTracking($task['id']);
} | Base | 1 |
protected function _mkdir($path, $name)
{
$path = $this->_joinPath($path, $name);
if ($this->connect->mkdir($path) === false) {
return false;
}
$this->options['dirMode'] && $this->connect->chmod($this->options['dirMode'], $path);
return $path;
} | Base | 1 |
public static function getId($id=''){
if(isset($id)){
$sql = sprintf("SELECT * FROM `menus` WHERE `id` = '%d'", $id);
$menus = Db::result($sql);
$n = Db::$num_rows;
}else{
$menus = '';
}
return $menus;
}
| Base | 1 |
public function index(Request $request)
{
/** @var User $user */
$user = auth()->user();
$page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data;
$collection = $this->repository->getAll();
$total = $collection->count();
$collection = $collection->slice(($page - 1) * $pageSize, $pageSize);
$currencies = new LengthAwarePaginator($collection, $total, $pageSize, $page);
$currencies->setPath(route('currencies.index'));
$defaultCurrency = $this->repository->getCurrencyByPreference(app('preferences')->get('currencyPreference', config('firefly.default_currency', 'EUR')));
$isOwner = true;
if (!$this->userRepository->hasRole($user, 'owner')) {
$request->session()->flash('info', (string) trans('firefly.ask_site_owner', ['owner' => config('firefly.site_owner')]));
$isOwner = false;
}
return prefixView('currencies.index', compact('currencies', 'defaultCurrency', 'isOwner'));
} | Compound | 4 |
public function uploadCustomLogoAction(Request $request)
{
$fileExt = File::getFileExtension($_FILES['Filedata']['name']);
if (!in_array($fileExt, ['svg', 'png', 'jpg'])) {
throw new \Exception('Unsupported file format');
}
if ($fileExt === 'svg' && stripos(file_get_contents($_FILES['Filedata']['tmp_name']), '<script')) {
throw new \Exception('Scripts in SVG files are not supported');
}
$storage = Tool\Storage::get('admin');
$storage->writeStream(self::CUSTOM_LOGO_PATH, fopen($_FILES['Filedata']['tmp_name'], 'rb'));
// set content-type to text/html, otherwise (when application/json is sent) chrome will complain in
// Ext.form.Action.Submit and mark the submission as failed
$response = $this->adminJson(['success' => true]);
$response->headers->set('Content-Type', 'text/html');
return $response;
} | Class | 2 |
static public function getHighestOrderNumber($_uid = 0) {
$where = '';
$sel_data = array();
if ($_uid > 0) {
$where = " WHERE `adminid` = :adminid";
$sel_data['adminid'] = $_uid;
}
$sql = "SELECT MAX(`logicalorder`) as `highestorder` FROM `" . TABLE_PANEL_TICKET_CATS . "`".$where.";";
$result_stmt = Database::prepare($sql);
$result = Database::pexecute_first($result_stmt, $sel_data);
return (isset($result['highestorder']) ? (int)$result['highestorder'] : 0);
} | Class | 2 |
$layout[$loc] = array_merge($layout[$loc],$data);
}
}
}
return $layout;
} | Class | 2 |
public static function thmMenu(){
$thm = Options::v('themes');
//$mod = self::modList();
//print_r($mod);
$list = '';
# code...
$data = self::data($thm);
if(isset($_GET['page'])
&& $_GET['page'] == 'themes'
&& isset($_GET['view'])
&& $_GET['view'] == 'options'){
$class = 'class="active"';
}else{
$class = "";
}
if (self::optionsExist($thm)) {
$active = (isset($_GET['page'])
&& $_GET['page'] == 'themes'
&& isset($_GET['view'])
&& $_GET['view'] == 'options')?"class=\"active\"":"";
$list .= "
<li $class>
<a href=\"index.php?page=themes&view=options\" $active>".$data['icon']." ".$data['name']."</a>
</li>";
}else{
$list = '';
}
return $list;
}
| Base | 1 |
foreach ($fields as $field => $title) {
if($i==0 && $j==0){
echo '<div class="row">';
}elseif($i==0 && $j>0){
echo '</div><div class="row">';
}
echo '<div class="col-md-6"><label class="checkbox-inline"><INPUT type=checkbox onclick="addHTML(\'<LI>' . $title . '</LI>\',\'names_div\',false);addHTML(\'<INPUT type=hidden name=fields[' . $field . '] value=Y>\',\'fields_div\',false);addHTML(\'\',\'names_div_none\',true);this.disabled=true">' . $title . '<label></div>';
/*if ($i % 2 == 0)
echo '</TR><TR>';*/
$i++;
if($i==2){
$i = 0;
}
$j++;
} | Base | 1 |
public function create_media_dir($params)
{
must_have_access();
$resp = array();
// $target_path = media_base_path() . 'uploaded' . DS;
$target_path = media_uploads_path();
$fn_path = media_base_path();
if (isset($_REQUEST['path']) and trim($_REQUEST['path']) != '') {
$_REQUEST['path'] = urldecode($_REQUEST['path']);
$fn_path = $target_path . DS . $_REQUEST['path'] . DS;
$fn_path = str_replace('..', '', $fn_path);
$fn_path = normalize_path($fn_path, false);
$target_path = $fn_path;
}
if (!isset($_REQUEST['name'])) {
$resp = array('error' => 'You must send new_folder parameter');
} else {
$fn_new_folder_path = $_REQUEST['name'];
$fn_new_folder_path = urldecode($fn_new_folder_path);
$fn_new_folder_path = str_replace('..', '', $fn_new_folder_path);
$fn_new_folder_path_new = $target_path . DS . $fn_new_folder_path;
$fn_path = normalize_path($fn_new_folder_path_new, false);
if (!is_dir($fn_path)) {
mkdir_recursive($fn_path);
$resp = array('success' => 'Folder ' . $fn_path . ' is created');
} else {
$resp = array('error' => 'Folder ' . $fn_new_folder_path . ' already exists');
}
}
return $resp;
} | Base | 1 |
$result[$index][1] = preg_replace(
"/" . $find . "/",
$replaceWith,
$row[0]
);
}
}
return $result;
} | Base | 1 |
public function fetchFormFromTemplate($id) {
} | Base | 1 |
function init_args() {
$args = new stdClass();
$args->req_id = isset($_REQUEST['requirement_id']) ? $_REQUEST['requirement_id'] : 0;
$args->compare_selected_versions = isset($_REQUEST['compare_selected_versions']);
$args->left_item_id = isset($_REQUEST['left_item_id']) ? intval($_REQUEST['left_item_id']) : -1;
$args->right_item_id = isset($_REQUEST['right_item_id']) ? intval($_REQUEST['right_item_id']) : -1;
$args->tproject_id = isset($_SESSION['testprojectID']) ? $_SESSION['testprojectID'] : 0;
$args->use_daisydiff = isset($_REQUEST['use_html_comp']);
$diffEngineCfg = config_get("diffEngine");
$args->context = null;
if( !isset($_REQUEST['context_show_all'])) {
$args->context = (isset($_REQUEST['context']) && is_numeric($_REQUEST['context'])) ? $_REQUEST['context'] : $diffEngineCfg->context;
}
return $args;
} | Base | 1 |
function cfdef_input_textbox( array $p_field_def, $p_custom_field_value, $p_required = '' ) {
echo '<input ', helper_get_tab_index(), ' type="text" id="custom_field_', $p_field_def['id']
, '" name="custom_field_', $p_field_def['id'], '" ', $p_required;
if( $p_field_def['length_max'] > 0 ) {
echo ' maxlength="' . $p_field_def['length_max'] . '"'
, ' size="' . min( 80, $p_field_def['length_max'] ) . '"';
} else {
echo ' maxlength="255" size="80"';
}
if( !empty( $p_field_def['valid_regexp'] ) ) {
# the custom field regex is evaluated with preg_match and looks for a partial match in the string
# however, the html property is matched for the whole string.
# unless we have explicit start and end tokens, adapt the html regex to allow a substring match.
$t_cf_regex = $p_field_def['valid_regexp'];
if( substr( $t_cf_regex, 0, 1 ) != '^' ) {
$t_cf_regex = '.*' . $t_cf_regex;
}
if( substr( $t_cf_regex, -1 ) != '$' ) {
$t_cf_regex .= '.*';
}
echo ' pattern="' . $t_cf_regex . '"';
}
echo ' value="' . string_attribute( $p_custom_field_value ) .'" />';
} | Base | 1 |
public function execute(&$params){
$action = new Actions;
$action->associationType = lcfirst(get_class($params['model']));
$action->associationId = $params['model']->id;
$action->subject = $this->parseOption('subject', $params);
$action->actionDescription = $this->parseOption('description', $params);
if($params['model']->hasAttribute('assignedTo'))
$action->assignedTo = $params['model']->assignedTo;
if($params['model']->hasAttribute('priority'))
$action->priority = $params['model']->priority;
if($params['model']->hasAttribute('visibility'))
$action->visibility = $params['model']->visibility;
if ($action->save()) {
return array (
true,
Yii::t('studio', "View created action: ").$action->getLink ()
);
} else {
return array(false, array_shift($action->getErrors()));
}
} | Base | 1 |
$module_views[$key]['name'] = gt($value['name']);
}
// look for a config form for this module's current view
// $controller->loc->mod = expModules::getControllerClassName($controller->loc->mod);
//check to see if hcview was passed along, indicating a hard-coded module
// if (!empty($controller->params['hcview'])) {
// $viewname = $controller->params['hcview'];
// } else {
// $viewname = $db->selectValue('container', 'view', "internal='".serialize($controller->loc)."'");
// }
// $viewconfig = $viewname.'.config';
// foreach ($modpaths as $path) {
// if (file_exists($path.'/'.$viewconfig)) {
// $fileparts = explode('_', $viewname);
// if ($fileparts[0]=='show'||$fileparts[0]=='showall') array_shift($fileparts);
// $module_views[$viewname]['name'] = ucwords(implode(' ', $fileparts)).' '.gt('View Configuration');
// $module_views[$viewname]['file'] =$path.'/'.$viewconfig;
// }
// }
// sort the views highest to lowest by filename
// we are reverse sorting now so our array merge
// will overwrite property..we will run array_reverse
// when we're finished to get them back in the right order
krsort($common_views);
krsort($module_views);
if (!empty($moduleconfig)) $common_views = array_merge($common_views, $moduleconfig);
$views = array_merge($common_views, $module_views);
$views = array_reverse($views);
return $views;
} | Base | 1 |
function insertServiceCategorieInDB(){
global $pearDB, $centreon;
if (testServiceCategorieExistence($_POST["sc_name"])){
$DBRESULT = $pearDB->query("INSERT INTO `service_categories` (`sc_name`, `sc_description`, `level`, `icon_id`, `sc_activate` )
VALUES ('".$_POST["sc_name"]."', '".$_POST["sc_description"]."', ".
(isset($_POST['sc_severity_level']) && $_POST['sc_type'] ? $pearDB->escape($_POST['sc_severity_level']):"NULL").", ".
(isset($_POST['sc_severity_icon']) && $_POST['sc_type'] ? $pearDB->escape($_POST['sc_severity_icon']) : "NULL").", ".
"'".$_POST["sc_activate"]["sc_activate"]."')"); | Base | 1 |
public static function generate_location_json( ) {
/* TODO: Try to track modification?
if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
$http_time = strtotime( $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
$mod_time = strtotime( $post->post_modified_gmt . ' GMT' );
if ($mod_time <= $http_time) {
return status_header(304); // Not modified
}
}
status_header(200);
header( 'Last-Modified: ' . mysql2date( 'D, d M Y H:i:s', $post->post_modified_gmt, false ) . ' GMT' );
header( 'Content-type: text/xml; charset='.get_settings('blog_charset'), true);
header( 'Cache-control: max-age=300, must-revalidate', true);
header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 300 ) . " GMT" );
header( 'Pragma:' );
*/
status_header(200);
header('Content-type: application/json; charset='.get_option('blog_charset'), true);
header('Cache-Control: no-cache;', true);
header('Expires: -1;', true);
$json = GeoMashup::get_locations_json($_REQUEST);
if ( isset( $_REQUEST['callback'] ) )
$json = $_REQUEST['callback'] . '(' . $json . ')';
echo $json;
}
| Class | 2 |
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 |
public function admin_download()
{
$this->autoRender = false;
$tmpDir = TMP . 'theme' . DS;
$Folder = new Folder();
$Folder->create($tmpDir);
$path = BASER_THEMES . $this->siteConfigs['theme'] . DS;
$Folder->copy([
'from' => $path,
'to' => $tmpDir . $this->siteConfigs['theme'],
'chmod' => 0777
]);
$Simplezip = new Simplezip();
$Simplezip->addFolder($tmpDir);
$Simplezip->download($this->siteConfigs['theme']);
$Folder->delete($tmpDir);
} | Base | 1 |
public function remove()
{
$project = $this->getProject();
$this->checkCSRFParam();
$column_id = $this->request->getIntegerParam('column_id');
if ($this->columnModel->remove($column_id)) {
$this->flash->success(t('Column removed successfully.'));
} else {
$this->flash->failure(t('Unable to remove this column.'));
}
$this->response->redirect($this->helper->url->to('ColumnController', 'index', array('project_id' => $project['id'])));
} | 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 saveconfig() {
global $db;
if (empty($this->params['id'])) return false;
$calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);
$calc = new $calcname($this->params['id']);
$conf = serialize($calc->parseConfig($this->params));
$calc->update(array('config'=>$conf));
expHistory::back();
} | Base | 1 |
public function testPopBeforeSmtpGood()
{
//Start a fake POP server
$pid = shell_exec('nohup ./runfakepopserver.sh >/dev/null 2>/dev/null & printf "%u" $!');
$this->pids[] = $pid;
sleep(2);
//Test a known-good login
$this->assertTrue(
POP3::popBeforeSmtp('localhost', 1100, 10, 'user', 'test', $this->Mail->SMTPDebug),
'POP before SMTP failed'
);
//Kill the fake server
shell_exec('kill -TERM '.escapeshellarg($pid));
sleep(2);
} | Class | 2 |
function addChannelPageTools($agencyid, $websiteId, $channelid, $channelType)
{
if ($channelType == 'publisher') {
$deleteReturlUrl = MAX::constructUrl(MAX_URL_ADMIN, 'affiliate-channels.php');
}
else {
$deleteReturlUrl = MAX::constructUrl(MAX_URL_ADMIN, 'channel-index.php');
}
//duplicate
addPageLinkTool($GLOBALS["strDuplicate"], MAX::constructUrl(MAX_URL_ADMIN, "channel-modify.php?duplicate=true&agencyid=$agencyid&affiliateid=$websiteId&channelid=$channelid&returnurl=".urlencode(basename($_SERVER['SCRIPT_NAME']))), "iconTargetingChannelDuplicate");
//delete
$deleteConfirm = phpAds_DelConfirm($GLOBALS['strConfirmDeleteChannel']);
addPageLinkTool($GLOBALS["strDelete"], MAX::constructUrl(MAX_URL_ADMIN, "channel-delete.php?token=" . urlencode(phpAds_SessionGetToken()) . "&agencyid=$agencyid&affiliateid=$websiteId&channelid=$channelid&returnurl=$deleteReturlUrl"), "iconDelete", null, $deleteConfirm);
} | Compound | 4 |
$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 |
foreach ($pkeys as $k) {
$where[] = $k . ' = "' . $row->$k . '"';
} | 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 static function render_page_process($PATH)
{
$search_query = $_REQUEST['search'];
$main = null;
if(strlen($search_query) < 4)
{
$main = '<h1>Search Failed</h1>';
$main .= '<p>Search Queries Must Be At Least Four Characters.</p>';
}
else
{
$main .= '<h1>Search Results For: ' . $search_query . '</h1>';
$category_matches = 0;
$tests = self::search_test_profiles($search_query);
if($tests != null)
{
$category_matches++;
$main .= '<h2>Test Profile Matches</h2>' . $tests . '<hr />';
}
$local_suites = self::search_local_test_suites($search_query);
if($local_suites != null)
{
$category_matches++;
$main .= '<h2>Local Test Suite Matches</h2>' . $local_suites . '<hr />';
}
$test_schedules = self::search_test_schedules($search_query);
if($test_schedules != null)
{
$category_matches++;
$main .= '<h2>Test Schedule Matches</h2>' . $test_schedules . '<hr />';
}
$test_results = self::search_test_results($search_query);
if($test_results != null)
{
$category_matches++;
$main .= '<h2>Test Result Matches</h2>' . $test_results . '<hr />';
}
$test_systems = self::search_test_systems($search_query);
if($test_systems != null)
{
$category_matches++;
$main .= '<h2>Test System Matches</h2>' . $test_systems . '<hr />';
}
if($category_matches == 0)
{
$main .= '<h2>No Matches Found</h2>';
}
}
echo phoromatic_webui_header_logged_in();
echo phoromatic_webui_main($main, phoromatic_webui_right_panel_logged_in());
echo phoromatic_webui_footer();
} | Base | 1 |
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'address' => '',
'primary_number' => 'numeric',
'secondary_number' => 'numeric',
'password' => 'sometimes',
'password_confirmation' => 'sometimes',
'image_path' => '',
'departments' => 'required'
];
} | Base | 1 |
foreach ($grpusers as $u) {
$emails[$u->email] = trim(user::getUserAttribution($u->id));
}
| Class | 2 |
public function testLogout()
{
$GLOBALS['cfg']['Server']['auth_swekey_config'] = '';
$GLOBALS['cfg']['CaptchaLoginPrivateKey'] = '';
$GLOBALS['cfg']['CaptchaLoginPublicKey'] = '';
$_REQUEST['old_usr'] = 'pmaolduser';
$GLOBALS['cfg']['LoginCookieDeleteAll'] = false;
$GLOBALS['cfg']['Servers'] = array(1);
$GLOBALS['server'] = 1;
$_COOKIE['pmaPass-1'] = 'test';
$this->object->authCheck();
$this->assertFalse(
isset($_COOKIE['pmaPass-1'])
);
} | Class | 2 |
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 |
static function description() {
return gt("This module is for managing categories in your store.");
} | Base | 1 |
public function register()
{
JSession::checkToken('post') or jexit(JText::_('JINVALID_TOKEN'));
// Get the application
$app = JFactory::getApplication();
// Get the form data.
$data = $this->input->post->get('user', array(), 'array');
// Get the model and validate the data.
$model = $this->getModel('Registration', 'UsersModel');
$form = $model->getForm();
if (!$form)
{
JError::raiseError(500, $model->getError());
return false;
}
$return = $model->validate($form, $data);
// Check for errors.
if ($return === false)
{
// Get the validation messages.
$errors = $model->getErrors();
// Push up to three validation messages out to the user.
for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++)
{
if ($errors[$i] instanceof Exception)
{
$app->enqueueMessage($errors[$i]->getMessage(), 'notice');
continue;
}
$app->enqueueMessage($errors[$i], 'notice');
}
// Save the data in the session.
$app->setUserState('users.registration.form.data', $data);
// Redirect back to the registration form.
$this->setRedirect('index.php?option=com_users&view=registration');
return false;
}
// Finish the registration.
$return = $model->register($data);
// Check for errors.
if ($return === false)
{
// Save the data in the session.
$app->setUserState('users.registration.form.data', $data);
// Redirect back to the registration form.
$message = JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $model->getError());
$this->setRedirect('index.php?option=com_users&view=registration', $message, 'error');
return false;
}
// Flush the data from the session.
$app->setUserState('users.registration.form.data', null);
return true;
} | Class | 2 |
private function getTaskLink()
{
$link = $this->taskLinkModel->getById($this->request->getIntegerParam('link_id'));
if (empty($link)) {
throw new PageNotFoundException();
}
return $link;
} | Base | 1 |
unset($return[$key]);
}
}
break;
}
return @array_change_key_case($return, CASE_UPPER);
} | Base | 1 |
private static function logoutAction()
{
if (wCMS::$currentPage === 'logout' && hash_equals($_REQUEST['token'], wCMS::generateToken())) {
unset($_SESSION['l'], $_SESSION['i'], $_SESSION['u'], $_SESSION['token']);
wCMS::redirect();
}
}
| Base | 1 |
public function open($savePath, $sessionName)
{
$return = (bool) $this->handler->open($savePath, $sessionName);
if (true === $return) {
$this->active = true;
}
return $return;
} | Base | 1 |
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 |
public static function recent_actions($function, $action, $limit=8)
{
global $DB;
global $user;
global $website;
// last month only!
$DB->query('
SELECT DISTINCT nvul.website, nvul.function, nvul.item, nvul.date
FROM nv_users_log nvul
WHERE nvul.user = '.protect($user->id).'
AND nvul.function = '.protect($function).'
AND nvul.item > 0
AND nvul.action = '.protect($action).'
AND nvul.website = '.protect($website->id).'
AND nvul.date > '.( core_time() - 30 * 86400).'
AND nvul.date = ( SELECT MAX(nvulm.date)
FROM nv_users_log nvulm
WHERE nvulm.function = nvul.function
AND nvulm.item = nvul.item
AND nvulm.item_title = nvul.item_title
AND nvulm.website = '.protect($website->id).'
AND nvulm.user = '.protect($user->id).'
)
ORDER BY nvul.date DESC
LIMIT '.$limit
);
| Base | 1 |
protected function configure() {
// set ARGS
$this->ARGS = $_SERVER['REQUEST_METHOD'] === 'POST'? $_POST : $_GET;
// set thumbnails path
$path = $this->options['tmbPath'];
if ($path) {
if (!file_exists($path)) {
if (@mkdir($path)) {
chmod($path, $this->options['tmbPathMode']);
} else {
$path = '';
}
}
if (is_dir($path) && is_readable($path)) {
$this->tmbPath = $path;
$this->tmbPathWritable = is_writable($path);
}
}
// set image manipulation library
$type = preg_match('/^(imagick|gd|auto)$/i', $this->options['imgLib'])
? strtolower($this->options['imgLib'])
: 'auto';
if (($type == 'imagick' || $type == 'auto') && extension_loaded('imagick')) {
$this->imgLib = 'imagick';
} else {
$this->imgLib = function_exists('gd_info') ? 'gd' : '';
}
// check archivers
if (empty($this->archivers['create'])) {
$this->disabled[] ='archive';
}
if (empty($this->archivers['extract'])) {
$this->disabled[] ='extract';
}
$_arc = $this->getArchivers();
if (empty($_arc['create'])) {
$this->disabled[] ='zipdl';
}
// check 'statOwner' for command `chmod`
if (empty($this->options['statOwner'])) {
$this->disabled[] ='chmod';
}
// check 'mimeMap'
if (!is_array($this->options['mimeMap'])) {
$this->options['mimeMap'] = array();
}
} | Base | 1 |
self::$collectedInfo[$params['name']] = array('definition' => $params, 'value' => $_FILES[$params['name']]);
}
} else {
if (isset(self::$collectedInfo[$params['name']]['value'])){
$valueContent = self::$collectedInfo[$params['name']]['value'];
$downloadLink = "<a href=\"http://".$_SERVER['HTTP_HOST'].erLhcoreClassDesign::baseurl('form/download').'/'.self::$collectedObject->id.'/'.self::$collectedObject->hash.'/'.$params['name']."\">Download (".htmlspecialchars($valueContent['name']).")</a>";
}
}
return "{$downloadLink}<input type=\"file\" name=\"{$params['name']}\" />";
}
| Class | 2 |
function columnUpdate($table, $col, $val, $where=1) {
$res = @mysqli_query($this->connection, "UPDATE `" . $this->prefix . "$table` SET `$col`='" . $val . "' WHERE $where");
/*if ($res == null)
return array();
$objects = array();
for ($i = 0; $i < mysqli_num_rows($res); $i++)
$objects[] = mysqli_fetch_object($res);*/
//return $objects;
} | Base | 1 |
public function getDisplayName ($plural=true) {
$moduleName = X2Model::getModuleName (get_class ($this));
return Modules::displayName ($plural, $moduleName);
} | Base | 1 |
function csrf_check($fatal = true)
{
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
return true;
}
csrf_start();
$name = $GLOBALS['csrf']['input-name'];
$ok = false;
$tokens = '';
do {
if (!isset($_POST[$name])) {
break;
}
// we don't regenerate a token and check it because some token creation
// schemes are volatile.
$tokens = $_POST[$name];
if (!csrf_check_tokens($tokens)) {
break;
}
$ok = true;
} while (false);
if ($fatal && !$ok) {
$callback = $GLOBALS['csrf']['callback'];
if (trim($tokens, 'A..Za..z0..9:;,') !== '') {
$tokens = 'hidden';
}
$callback($tokens);
exit;
}
return $ok;
} | Compound | 4 |
private function isWindows()
{
return DIRECTORY_SEPARATOR !== '/';
} | Class | 2 |