示例#1
0
 public function index()
 {
     $db = new Database();
     $incidents = $db->query("SELECT incident.id, incident_title, \n\t\t\t\t\t\t\t\t incident_description, incident_verified, \n\t\t\t\t\t\t\t\t location.latitude, location.longitude, alert_sent.incident_id\n\t\t\t\t\t\t\t\t FROM incident INNER JOIN location ON incident.location_id = location.id\n\t\t\t\t\t\t\t\t LEFT OUTER JOIN alert_sent ON incident.id = alert_sent.incident_id");
     $config = kohana::config('alerts');
     $sms_from = NULL;
     $settings = ORM::factory('settings', 1);
     if ($settings->loaded == true) {
         // Get SMS Numbers
         if (!empty($settings->sms_no3)) {
             $sms_from = $settings->sms_no3;
         } elseif (!empty($settings->sms_no2)) {
             $sms_from = $settings->sms_no2;
         } elseif (!empty($settings->sms_no1)) {
             $sms_from = $settings->sms_no1;
         } else {
             $sms_from = "000";
         }
         // User needs to set up an SMS number
     }
     foreach ($incidents as $incident) {
         if ($incident->incident_id != NULL) {
             continue;
         }
         $verified = (int) $incident->incident_verified;
         if ($verified) {
             $latitude = (double) $incident->latitude;
             $longitude = (double) $incident->longitude;
             $proximity = new Proximity($latitude, $longitude);
             $alertees = $this->_get_alertees($proximity);
             foreach ($alertees as $alertee) {
                 $alert_type = (int) $alertee->alert_type;
                 if ($alert_type == 1) {
                     $sms = new Eflyer();
                     $sms->user = $settings->eflyer_username;
                     $sms->password = $settings->eflyer_password;
                     $sms->use_ssl = false;
                     $sms->sms();
                     $message = $incident->incident_description;
                     if ($sms->send($alertee->alert_recipient, $message) == "OK") {
                         $db->insert('alert_sent', array('alert_id' => $alertee->id, 'incident_id' => $incident->id, 'alert_date' => date("Y-m-d H:i:s")));
                         $db->clear_cache(true);
                     }
                 } elseif ($alert_type == 2) {
                     $to = $alertee->alert_recipient;
                     $from = $config['alerts_email'];
                     $subject = $incident->incident_title;
                     $message = $incident->incident_description;
                     if (email::send($to, $from, $subject, $message, TRUE) == 1) {
                         $db->insert('alert_sent', array('alert_id' => $alertee->id, 'incident_id' => $incident->id, 'alert_date' => date("Y-m-d H:i:s")));
                         $db->clear_cache(true);
                     }
                 }
             }
         }
     }
 }
示例#2
0
 public function load()
 {
     $db = new Database();
     $db->delete('Users', 'StudentId is not null');
     $db->delete('Students', '1=1');
     $db->select('Settings', 'SrProjectUrl,SrProjectToken');
     $settings = $db->getResult();
     $students = json_decode(file_get_contents($settings['SrProjectUrl'] . '/getAll/' . $settings['SrProjectToken']));
     foreach ($students as $student) {
         $db->insert('Students', array('id' => $student->id, 'Project' => $student->projectTitle, 'Location' => 'TBA'));
         $db->insert('Users', array('Email' => $student->email . '@fiu.edu', 'FirstName' => ucfirst($student->firstName), 'LastName' => ucfirst($student->lastName), 'StudentId' => $student->id, 'Roles' => 'student', 'DefaultRole' => 'student'));
     }
     return true;
 }
示例#3
0
 /**
  * @param ResultWrapper $res
  * @param Database $dbw
  * @return null|int
  */
 function convertOptionBatch($res, $dbw)
 {
     $id = null;
     foreach ($res as $row) {
         $this->mConversionCount++;
         $insertRows = [];
         foreach (explode("\n", $row->user_options) as $s) {
             $m = [];
             if (!preg_match("/^(.[^=]*)=(.*)\$/", $s, $m)) {
                 continue;
             }
             // MW < 1.16 would save even default values. Filter them out
             // here (as in User) to avoid adding many unnecessary rows.
             $defaultOption = User::getDefaultOption($m[1]);
             if (is_null($defaultOption) || $m[2] != $defaultOption) {
                 $insertRows[] = ['up_user' => $row->user_id, 'up_property' => $m[1], 'up_value' => $m[2]];
             }
         }
         if (count($insertRows)) {
             $dbw->insert('user_properties', $insertRows, __METHOD__, ['IGNORE']);
         }
         $dbw->update('user', ['user_options' => ''], ['user_id' => $row->user_id], __METHOD__);
         $id = $row->user_id;
     }
     return $id;
 }
示例#4
0
 /**
  * Common function for databases that don't understand the MySQLish syntax of interwiki.sql.
  *
  * @return Status
  */
 public function populateInterwikiTable()
 {
     $status = $this->getConnection();
     if (!$status->isOK()) {
         return $status;
     }
     $this->db->selectDB($this->getVar('wgDBname'));
     if ($this->db->selectRow('interwiki', '*', [], __METHOD__)) {
         $status->warning('config-install-interwiki-exists');
         return $status;
     }
     global $IP;
     MediaWiki\suppressWarnings();
     $rows = file("{$IP}/maintenance/interwiki.list", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
     MediaWiki\restoreWarnings();
     $interwikis = [];
     if (!$rows) {
         return Status::newFatal('config-install-interwiki-list');
     }
     foreach ($rows as $row) {
         $row = preg_replace('/^\\s*([^#]*?)\\s*(#.*)?$/', '\\1', $row);
         // strip comments - whee
         if ($row == "") {
             continue;
         }
         $row .= "|";
         $interwikis[] = array_combine(['iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid'], explode('|', $row));
     }
     $this->db->insert('interwiki', $interwikis, __METHOD__);
     return Status::newGood();
 }
示例#5
0
 public static function write_log($modul, $aksi, $referensi)
 {
     $db = new Database();
     $pesan = "modul " . strtoupper($modul) . " aksi " . strtoupper($aksi) . " referensi " . $referensi;
     $ip = '';
     if ($_SERVER['HTTP_CLIENT_IP']) {
         $ip = $_SERVER['HTTP_CLIENT_IP'];
     } elseif ($_SERVER['HTTP_X_FORWARDED_FOR']) {
         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
     } elseif ($_SERVER['HTTP_X_FORWARDED']) {
         $ip = $_SERVER['HTTP_X_FORWARDED'];
     } elseif ($_SERVER['HTTP_FORWARDED_FOR']) {
         $ip = $_SERVER['HTTP_FORWARDED_FOR'];
     } elseif ($_SERVER['HTTP_FORWARDED']) {
         $ip = $_SERVER['HTTP_FORWARDED'];
     } elseif ($_SERVER['REMOTE_ADDR']) {
         $ip = $_SERVER['REMOTE_ADDR'];
     } else {
         $ip = 'UNKNOWN';
     }
     $now = date('Y-m-d h:i:s');
     $data = array('USER' => Session::get('user'), 'AKTIFITAS_EL' => $pesan, 'TIME_STAMP_EL' => $now, 'IP_ADDRESS_EL' => $ip);
     //        var_dump($data);
     //        echo Session::get('user')." ".$pesan." ".$ip." ".$now;
     $db->insert('d_entry_log', $data);
 }
示例#6
0
文件: tag.php 项目: 4otaku/4otaku
 public function process()
 {
     $tag = $this->get('tag');
     $type = $this->get('type');
     if (empty($tag)) {
         throw new Error_Api('Пропущено обязательное поле: tag', Error_Api::MISSING_INPUT);
     }
     if (empty($type)) {
         throw new Error_Api('Пропущено обязательное поле: type', Error_Api::MISSING_INPUT);
     }
     if (!array_key_exists($type, $this->types)) {
         throw new Error_Api('Неправильно заполнено поле: type', Error_Api::INCORRECT_INPUT);
     }
     $color = $this->types[$type];
     $tag = trim(undo_safety($tag));
     $args = array($tag, '|' . $tag . '|', $tag);
     $exists = Database::get_field('tag', 'alias', 'name = ? or locate(?, variants) or alias = ?', $args);
     if ($exists) {
         $alias = $exists;
     } else {
         $alias = Transform_Meta::make_alias($tag);
         Database::insert('tag', array('alias' => $alias, 'name' => $tag, 'variants' => '|'));
         $this->add_error(Error_Api::UNKNOWN_TAG);
     }
     Database::update('tag', array('color' => $color), 'alias = ?', $alias);
     $this->set_success(true);
     $this->add_answer('tag', $alias);
 }
示例#7
0
    public function add($concepto, $moneda, $monto, $tipo_op)
    {
        include_once '../db.php';
        $db = new Database();
        $db->connect();
        $valores = array();
        $valores[0] = '"' . $concepto . '"';
        $valores[1] = $moneda;
        $valores[2] = $monto;
        $valores[3] = '"' . date('Y-m-d') . '"';
        $valores[4] = $monto;
        $valores[5] = $tipo_op;
        $valores[6] = '"' . $_SESSION[userPagos] . '"';
        $valores[7] = 1;
        $valores[8] = 0;
        if ($moneda == 1) {
            $dolar = new dolar();
            $dolarCompra = $dolar->getDolar();
            $valores[4] = round($monto * $dolarCompra, 2);
        }
        $idCreated = $db->insert('pagos', $valores, 'concepto,moneda,monto,fecha,pesos,tipo_op,editor,activo,id_host');
        $monedaOutput = array('£', 'U$D');
        $htm = '<li id="rowNro' . $idCreated . '" class="row rowAdded">
				<p class="tableConcepto">
					' . $concepto . '
					<span class="tableFecha">' . date('d-m-Y') . '</span>
				</p>
				<span class="tableMonto tipo_op' . $tipo_op . '"><span class="fontMoneda' . $moneda . '">' . $monedaOutput[$moneda] . '</span> ' . $monto . '</span>
				<span class="tableOpciones">
					<a class="modifyOpTable" href="javascript:;" onClick="toggleEditor(5,' . $idCreated . ',\'' . str_replace("'", "\\'", $concepto) . '\',\'' . $monto . '\',' . $moneda . ',' . $tipo_op . ')">&nbsp;</a>
		<a class="deleteOpTable" href="javascript:;" onClick="delPayment(\'payment\',' . $idCreated . ',\'' . str_replace("'", "\\'", $concepto) . '\',0)">&nbsp;</a>
				</span>
			</li>';
        return $htm;
    }
示例#8
0
    public function add($concepto, $moneda, $monto, $tipo_op)
    {
        include_once '../db.php';
        $db = new Database();
        $db->connect();
        $valores = array();
        $valores[0] = '"' . $concepto . '"';
        $valores[1] = $moneda;
        $valores[2] = $monto;
        $valores[3] = '"' . date('Y-m-d') . '"';
        $valores[4] = $monto;
        $valores[5] = $tipo_op;
        $valores[6] = '"pepe"';
        $valores[7] = 1;
        $valores[8] = 0;
        if ($moneda == 1) {
            $dolar = new dolar();
            $dolarCompra = $dolar->getDolar();
            $valores[4] = round($monto * $dolarCompra, 2);
        }
        $idCreated = $db->insert('pagos', $valores, 'concepto,moneda,monto,fecha,pesos,tipo_op,editor,activo,id_host');
        $monedaOutput = array('£', 'U$D');
        $htm = '<li id="rowNro' . $idCreated . '" class="row rowAdded">
					<span class="col1">' . date('d-m-Y') . '</span>
					<span class="col2">' . $concepto . '</span>
					<span class="col3 tipo_op' . $tipo_op . '">' . $monedaOutput[$moneda] . ' ' . $monto . '</span>
					<span class="col4">
						<a class="modifyOpTable" href="javascript:;" onClick="showModGastos(' . $idCreated . ',\'' . str_replace("'", "\\'", $concepto) . '\',\'' . $monto . '\',' . $moneda . ',' . $tipo_op . ')">&nbsp;</a>
                    	<a class="deleteOpTable" href="javascript:;" onClick="gastos(\'del\',' . $idCreated . ',\'' . str_replace("'", "\\'", $concepto) . '\')">&nbsp;</a>
					</span>
				</li>
				';
        return $htm;
    }
示例#9
0
 /**
  * Provides the services/data_utils/bulk_verify service. This takes a report plus params (json object) in the $_POST
  * data and verifies all the records returned by the report according to the filter. Pass ignore=true to allow this to 
  * ignore any verification check rule failures (use with care!).
  */
 public function bulk_verify()
 {
     $db = new Database();
     $this->authenticate('write');
     $report = $_POST['report'];
     $params = json_decode($_POST['params'], true);
     $params['sharing'] = 'verification';
     $websites = $this->website_id ? array($this->website_id) : null;
     $this->reportEngine = new ReportEngine($websites, $this->user_id);
     try {
         // Load the report used for the verification grid with the same params
         $data = $this->reportEngine->requestReport("{$report}.xml", 'local', 'xml', $params);
         // now get a list of all the occurrence ids
         $ids = array();
         foreach ($data['content']['records'] as $record) {
             if ($record['record_status'] !== 'V' && (!empty($record['pass']) || $_POST['ignore'] === 'true')) {
                 $ids[$record['occurrence_id']] = $record['occurrence_id'];
                 $db->insert('occurrence_comments', array('occurrence_id' => $record['occurrence_id'], 'comment' => 'This record is assumed to be correct', 'created_by_id' => $this->user_id, 'created_on' => date('Y-m-d H:i:s'), 'updated_by_id' => $this->user_id, 'updated_on' => date('Y-m-d H:i:s')));
             }
         }
         $db->from('occurrences')->set(array('record_status' => 'V', 'verified_by_id' => $this->user_id, 'verified_on' => date('Y-m-d H:i:s'), 'updated_by_id' => $this->user_id, 'updated_on' => date('Y-m-d H:i:s')))->in('id', array_keys($ids))->update();
         echo count($ids);
         $db->from('cache_occurrences')->set(array('record_status' => 'V', 'cache_updated_on' => date('Y-m-d H:i:s')))->in('id', array_keys($ids))->update();
     } catch (Exception $e) {
         echo $e->getMessage();
         error::log_error('Exception during bulk verify', $e);
     }
 }
 /**
  * @since 2.3
  *
  * @param integer $sid
  * @param array $dependencyList
  */
 public function updateDependencyList($sid, array $dependencyList)
 {
     $this->connection->beginAtomicTransaction(__METHOD__);
     // Before an insert, delete all entries that for the criteria which is
     // cheaper then doing an individual upsert or selectRow, this also ensures
     // that entries are self-corrected for dependencies matched
     $this->connection->delete(SMWSQLStore3::QUERY_LINKS_TABLE, array('s_id' => $sid), __METHOD__);
     if ($sid == 0) {
         return $this->connection->endAtomicTransaction(__METHOD__);
     }
     $inserts = array();
     foreach ($dependencyList as $dependency) {
         $oid = $this->getIdForSubject($dependency);
         if ($oid < 1) {
             continue;
         }
         $inserts[$sid . $oid] = array('s_id' => $sid, 'o_id' => $oid);
     }
     if ($inserts === array()) {
         return $this->connection->endAtomicTransaction(__METHOD__);
     }
     // MW's multi-array insert needs a numeric dimensional array but the key
     // was used with a hash to avoid duplicate entries hence the re-copy
     $inserts = array_values($inserts);
     wfDebugLog('smw', __METHOD__ . ' insert for SID ' . $sid . "\n");
     $this->connection->insert(SMWSQLStore3::QUERY_LINKS_TABLE, $inserts, __METHOD__);
     $this->connection->endAtomicTransaction(__METHOD__);
 }
示例#11
0
文件: input.php 项目: 4otaku/draw
	public function add ($query) {

		list($place, $item_id) = $this->parse_referer($query);

		if (!empty($query['parent'])) {
			$root = Database::get_field('comment', 'root', $query['parent']);

			if (empty($root)) {
				$root = $query['parent'];
			}
		} else {
			$root = 0;
		}

		$insert = array(
			'root' => $root,
			'parent' => $query['parent'],
			'place' => $place,
			'item_id' => $item_id,
			'area' => 'main',
			'username' => $query['name'],
			'email' => $query['email'],
			'ip' => Globals::$user_data['ip'],
			'cookie' => Globals::$user_data['cookie'],
			'text' => Transform_Text::format($query['text']),
			'pretty_text' => $query['text'],
		);

		Database::insert('comment', $insert);
		
		Database::update($place, $item_id, array('comments' => '++'));

		$this->redirect_address = $this->referer;
	}
示例#12
0
 function copyExactMatch($srcTable, $dstTable, $copyPos)
 {
     $numRowsCopied = 0;
     $srcRes = $this->dbw->select($srcTable, '*', ['log_timestamp' => $copyPos], __METHOD__);
     $dstRes = $this->dbw->select($dstTable, '*', ['log_timestamp' => $copyPos], __METHOD__);
     if ($srcRes->numRows()) {
         $srcRow = $srcRes->fetchObject();
         $srcFields = array_keys((array) $srcRow);
         $srcRes->seek(0);
         $dstRowsSeen = [];
         # Make a hashtable of rows that already exist in the destination
         foreach ($dstRes as $dstRow) {
             $reducedDstRow = [];
             foreach ($srcFields as $field) {
                 $reducedDstRow[$field] = $dstRow->{$field};
             }
             $hash = md5(serialize($reducedDstRow));
             $dstRowsSeen[$hash] = true;
         }
         # Copy all the source rows that aren't already in the destination
         foreach ($srcRes as $srcRow) {
             $hash = md5(serialize((array) $srcRow));
             if (!isset($dstRowsSeen[$hash])) {
                 $this->dbw->insert($dstTable, (array) $srcRow, __METHOD__);
                 $numRowsCopied++;
             }
         }
     }
     return $numRowsCopied;
 }
 /**
  * @since 2.3
  *
  * @param integer $sid
  * @param array $dependencyList
  */
 public function updateDependencyList($sid, array $dependencyList)
 {
     $this->connection->beginAtomicTransaction(__METHOD__);
     // Before an insert, delete all entries that for the criteria which is
     // cheaper then doing an individual upsert or selectRow, this also ensures
     // that entries are self-corrected for dependencies matched
     $this->connection->delete(SMWSQLStore3::QUERY_LINKS_TABLE, array('s_id' => $sid), __METHOD__);
     if ($sid == 0) {
         return $this->connection->endAtomicTransaction(__METHOD__);
     }
     $inserts = array();
     foreach ($dependencyList as $dependency) {
         $oid = $this->getIdForSubject($dependency);
         // If the ID_TABLE didn't contained an valid ID then we create one ourselves
         // to ensure that object entities are tracked from the start
         // This can happen when a query is added with object reference that have not
         // yet been referenced as annotation and therefore do not recognized as
         // value annotation
         if ($oid < 1 && ($oid = $this->tryToMakeIdForSubject($dependency)) < 1) {
             continue;
         }
         $inserts[$sid . $oid] = array('s_id' => $sid, 'o_id' => $oid);
     }
     if ($inserts === array()) {
         return $this->connection->endAtomicTransaction(__METHOD__);
     }
     // MW's multi-array insert needs a numeric dimensional array but the key
     // was used with a hash to avoid duplicate entries hence the re-copy
     $inserts = array_values($inserts);
     wfDebugLog('smw', __METHOD__ . ' insert for SID ' . $sid . "\n");
     $this->connection->insert(SMWSQLStore3::QUERY_LINKS_TABLE, $inserts, __METHOD__);
     $this->connection->endAtomicTransaction(__METHOD__);
 }
示例#14
0
 /**
  * Create a video chat
  * @param int $fromUser The sender user
  * @param int $toUser The receiver user
  * @return int The created video chat id. Otherwise return false
  */
 public static function createRoom($fromUser, $toUser)
 {
     $fromUserInfo = api_get_user_info($fromUser);
     $toUserInfo = api_get_user_info($toUser);
     $chatName = vsprintf(get_lang('VideoChatBetweenUserXAndUserY'), [$fromUserInfo['firstname'], $toUserInfo['firstname']]);
     return Database::insert(Database::get_main_table(TABLE_MAIN_CHAT_VIDEO), ['from_user' => intval($fromUser), 'to_user' => intval($toUser), 'room_name' => $chatName, 'datetime' => api_get_utc_datetime()]);
 }
 public function process(array $documents, &$context)
 {
     $doc = $documents[self::URL_HISTORY];
     $dom = self::getDOM($doc);
     $xpath = new DOMXPath($dom);
     Database::delete('userhistory', ['user_id' => $context->user->id]);
     $data = [];
     $nodes = $xpath->query('//table//td[@class = \'borderClass\']/..');
     foreach ($nodes as $node) {
         //basic info
         $link = $node->childNodes->item(0)->childNodes->item(0)->getAttribute('href');
         preg_match('/(\\d+)\\/?$/', $link, $matches);
         $media = strpos($link, 'manga') !== false ? Media::Manga : Media::Anime;
         $mediaMalId = intval($matches[0]);
         $progress = Strings::makeInteger($node->childNodes->item(0)->childNodes->item(2)->nodeValue);
         //parse time
         //That's what MAL servers output for MG client
         if (isset($doc->headers['Date'])) {
             date_default_timezone_set('UTC');
             $now = strtotime($doc->headers['Date']);
         } else {
             $now = time();
         }
         date_default_timezone_set('America/Los_Angeles');
         $hour = date('H', $now);
         $minute = date('i', $now);
         $second = date('s', $now);
         $day = date('d', $now);
         $month = date('m', $now);
         $year = date('Y', $now);
         $dateString = $node->childNodes->item(2)->nodeValue;
         if (preg_match('/(\\d*) seconds? ago/', $dateString, $matches)) {
             $second -= intval($matches[1]);
         } elseif (preg_match('/(\\d*) minutes? ago/', $dateString, $matches)) {
             $second -= intval($matches[1]) * 60;
         } elseif (preg_match('/(\\d*) hours? ago/', $dateString, $matches)) {
             $minute -= intval($matches[1]) * 60;
         } elseif (preg_match('/Today, (\\d*):(\\d\\d) (AM|PM)/', $dateString, $matches)) {
             $hour = intval($matches[1]);
             $minute = intval($matches[2]);
             $hour += ($matches[3] == 'PM' and $hour != 12) ? 12 : 0;
         } elseif (preg_match('/Yesterday, (\\d*):(\\d\\d) (AM|PM)/', $dateString, $matches)) {
             $hour = intval($matches[1]);
             $minute = intval($matches[2]);
             $hour += ($matches[3] == 'PM' and $hour != 12) ? 12 : 0;
             $hour -= 24;
         } elseif (preg_match('/(\\d\\d)-(\\d\\d)-(\\d\\d), (\\d*):(\\d\\d) (AM|PM)/', $dateString, $matches)) {
             $year = intval($matches[3]) + 2000;
             $month = intval($matches[1]);
             $day = intval($matches[2]);
             $hour = intval($matches[4]);
             $minute = intval($matches[5]);
             $hour += ($matches[6] == 'PM' and $hour != 12) ? 12 : 0;
         }
         $timestamp = mktime($hour, $minute, $second, $month, $day, $year);
         date_default_timezone_set('UTC');
         $data[] = ['user_id' => $context->user->id, 'mal_id' => $mediaMalId, 'media' => $media, 'progress' => $progress, 'timestamp' => date('Y-m-d H:i:s', $timestamp)];
     }
     Database::insert('userhistory', $data);
 }
示例#16
0
 public static function display()
 {
     $messages = "";
     if ($_POST['cc_form'] === 'add-group') {
         $group = $_POST['group'];
         $rows = Database::select('users', 'name', array('name = ? AND type = ?', $group, 'group'), null, 1)->fetch(PDO::FETCH_ASSOC);
         if (!empty($rows)) {
             $messages .= Message::error(__('admin', 'group-in-use'));
         } else {
             $row = DB::select('users', array('data'), array('users_id = ?', $_GET['parent']))->fetch(PDO::FETCH_ASSOC);
             $inheritance = unserialize($row['data']);
             $inheritance = $inheritance['permissions'];
             $result = Database::insert('users', array('name' => filter('admin_add_group_name', $group), 'type' => 'group', 'group' => '-1', 'data' => serialize(filter('admin_add_group_data', array('permissions' => $inheritance)))));
             if ($result === 1) {
                 $messages .= Message::success(__('admin', 'group-added'));
             }
         }
     }
     $form = new Form('self', 'post', 'add-group');
     $form->startFieldset(__("admin", 'group-information'));
     $form->addInput(__('admin', 'group-name'), 'text', 'group', self::get('group'));
     $groups = Users::allGroups();
     foreach ($groups as $key => $value) {
         $groups[$value->getId()] = $value->getName();
     }
     $form->addSelectList(__('admin', 'inherit-permissions'), 'parent', $groups);
     plugin('admin_add_group_custom_fields', array(&$form));
     $form->addSubmit('', 'add-group', __('admin', 'add-group'));
     $form->endFieldset();
     plugin('admin_add_group_custom_fieldset', array(&$form));
     $form = $form->endAndGetHTML();
     return array(__('admin', 'add-group'), $messages . $form);
 }
示例#17
0
文件: student.php 项目: Prafful-p/php
 public function Insertion($valuePost)
 {
     echo "hello";
     if (!preg_match("/^[0-9]*\$/", $valuePost['contact'])) {
         $error = "contact format is wrong";
     } elseif (!preg_match("/^[0-9.]*\$/", $valuePost['secondary'])) {
         $error = "Percentage format is wrong";
     } elseif (!preg_match("/^[0-9.]*\$/", $valuePost['senior'])) {
         $error = "Percentage format is wrong";
     } elseif ($valuePost['fn'] != "jpg" && $valuePost['fn'] != "png" && $valuePost['fn'] != "jpeg" && $valuePost['fn'] != "gif") {
         if (move_uploaded_file($_FILES['img']['tmp_name'], $valuePost['target'])) {
         } else {
             $error = "Sorry Try Again";
         }
     } else {
         echo "SIZE | TYPE MISTMATCH :( Try Again";
     }
     if (isset($error)) {
         return $error;
     } else {
         $firstname = $valuePost['firstname'];
         $lastname = $valuePost['lastname'];
         $fathername = $valuePost['fathername'];
         $dob = $valuePost['dob'];
         $sex = $valuePost['sex'];
         $contact = $valuePost['contact'];
         $email = $valuePost['email'];
         $secondary = $valuePost['secondary'];
         $senior = $valuePost['senior'];
         $fn = $valuePost['fn'];
         $sql = "INSERT INTO registration (firstname,lastname,fathername,dob,sex,contact,email,secondary,senior,img)\n                VALUES ('{$firstname}','{$lastname}','{$fathername}','{$dob}','{$sex}','{$contact}','{$email}','{$secondary}','{$senior}','{$fn}')";
         $db = new Database();
         $db->insert($sql);
     }
 }
示例#18
0
文件: art.php 项目: 4otaku/4otaku
	function edit_art_groups() {
		global $check;
		if ($check->num(query::$post['id']) && query::$post['type'] == 'art' && is_array(query::$post['group'])) {

			$qroups = array_filter(array_unique(query::$post['group']));

			foreach ($qroups as $key => $group) {
				if (Database::get_count('art_pool',
					'id = ? and password != "" and password != ?',
					array($group, md5(query::$post['password'])))
				) {
					unset($qroups[$key]);
				}
			}

			foreach ($qroups as $group) {
				$order = Database::order('order')->
					get_field('art_in_pool', 'order', 'pool_id = ?', $group);

				Database::insert('art_in_pool', array(
					'art_id' => query::$post['id'],
					'pool_id' => $group,
					'order' => $order + 1
				));
			}
		}
	}
示例#19
0
    public function add($id_host, $concepto)
    {
        include_once '../db.php';
        $db = new Database();
        $db->connect();
        $valores = array();
        $valores[0] = '"' . $concepto . '"';
        $valores[1] = 0;
        $valores[2] = 360;
        $valores[3] = '"' . date('Y-m-d') . '"';
        $valores[4] = 360;
        $valores[5] = 1;
        $valores[6] = '"' . $_SESSION[userPagos] . '"';
        $valores[7] = 1;
        $valores[8] = $id_host;
        $idCreated = $db->insert('pagos', $valores, 'concepto,moneda,monto,fecha,pesos,tipo_op,editor,activo,id_host');
        $this->updateVencimiento($id_host, 1);
        $htm = '<li id="rowNro' . $idCreated . '" class="row rowAdded">
					<p class="tableConcepto">
						' . $concepto . '
						<span class="tableFecha">' . date('d-m-Y') . '</span>
					</p>
					<span class="tableMonto tipo_op1"><span class="fontMoneda0">£</span> 360</span>
					<span class="tableOpciones">
						<a class="modifyOpTable disabledOp" href="javascript:;">&nbsp;</a>
						<a class="deleteOpTable" href="javascript:;" onClick="delPayment(\'hosting\',' . $idCreated . ',\'' . $concepto . '\',\'' . $id_host . '\')">&nbsp;</a>
					</span>
				</li>';
        return $htm;
    }
示例#20
0
 public function save()
 {
     if (!$this->tableName || !$this->databaseFields) {
         return;
     }
     $invalid = false;
     $values = array();
     foreach ($this->databaseFields as $fieldName) {
         if (isset($this->{$fieldName})) {
             if (is_object($this->{$fieldName})) {
                 $values[$fieldName] = $this->{$fieldName}->id;
             } else {
                 $values[$fieldName] = $this->{$fieldName};
             }
         }
     }
     if (!$invalid) {
         if ($this->id == null) {
             $this->id = Database::insert($this->tableName, $values);
         } else {
             Database::update($this->tableName, $this->id, $values);
         }
         $this->saved = true;
     }
 }
示例#21
0
 private function addCoreDBData()
 {
     if ($this->db->getType() == 'oracle') {
         # Insert 0 user to prevent FK violations
         # Anonymous user
         if (!$this->db->selectField('user', '1', ['user_id' => 0])) {
             $this->db->insert('user', ['user_id' => 0, 'user_name' => 'Anonymous'], __METHOD__, ['IGNORE']);
         }
         # Insert 0 page to prevent FK violations
         # Blank page
         if (!$this->db->selectField('page', '1', ['page_id' => 0])) {
             $this->db->insert('page', ['page_id' => 0, 'page_namespace' => 0, 'page_title' => ' ', 'page_restrictions' => null, 'page_is_redirect' => 0, 'page_is_new' => 0, 'page_random' => 0, 'page_touched' => $this->db->timestamp(), 'page_latest' => 0, 'page_len' => 0], __METHOD__, ['IGNORE']);
         }
     }
     User::resetIdByNameCache();
     // Make sysop user
     $user = static::getTestSysop()->getUser();
     // Make 1 page with 1 revision
     $page = WikiPage::factory(Title::newFromText('UTPage'));
     if ($page->getId() == 0) {
         $page->doEditContent(new WikitextContent('UTContent'), 'UTPageSummary', EDIT_NEW, false, $user);
         // doEditContent() probably started the session via
         // User::loadFromSession(). Close it now.
         if (session_id() !== '') {
             session_write_close();
             session_id('');
         }
     }
 }
示例#22
0
/**
 * Save the score for a HP quiz. Can be used by the learnpath tool as well
 * for HotPotatoes quizzes. When coming from the learning path, we
 * use the session variables telling us which item of the learning path has to
 * be updated (score-wise)
 * @param	string	File is the exercise name (the file name for a HP)
 * @param	integer	Score to save inside the tracking tables (HP and learnpath)
 * @return	void
 */
function save_scores($file, $score)
{
    global $origin;
    $TABLETRACK_HOTPOTATOES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
    $_user = api_get_user_info();
    // if tracking is disabled record nothing
    $weighting = 100;
    // 100%
    $date = api_get_utc_datetime();
    $c_id = api_get_course_int_id();
    if ($_user['user_id']) {
        $user_id = $_user['user_id'];
    } else {
        // anonymous
        $user_id = "NULL";
    }
    $params = ['exe_name' => $file, 'exe_user_id' => $user_id, 'exe_date' => $date, 'c_id' => $c_id, 'exe_result' => $score, 'exe_weighting' => $weighting];
    Database::insert($TABLETRACK_HOTPOTATOES, $params);
    if ($origin == 'learnpath') {
        //if we are in a learning path, save the score in the corresponding
        //table to get tracking in there as well
        global $jscript2run;
        //record the results in the learning path, using the SCORM interface (API)
        $jscript2run .= "<script>\n            \$(document).ready(function() {\n                //API_obj = window.frames.window.content.API;\n                //API_obj = \$('content_id').context.defaultView.content.API; //works only in FF\n                //API_obj = window.parent.frames.window.top.API;\n                API_obj = window.top.API;\n                API_obj.void_save_asset('{$score}', '{$weighting}', 0, 'completed');\n            });\n        </script>";
    }
}
示例#23
0
 protected function do_add($data)
 {
     if (!isset($data['set']) || !is_array($data['set'])) {
         return array('success' => false);
     }
     if (!empty($data['start'])) {
         $utc = $data['utc'] + 240;
         $start = date('Y-m-d G:i:s', strtotime($data['start']) + $utc * 60);
     } else {
         $start = '';
     }
     $sets = array();
     foreach ($data['set'] as $set) {
         if (preg_match('/[^-\\d\\.a-z]/ui', $set)) {
             continue;
         }
         $set = Database::get_full_row('set', 'id = ?', $set);
         if (empty($set)) {
             continue;
         }
         $sets[] = $set;
         if (!$set['grabbed']) {
             Grabber::get_set($set['id']);
         }
     }
     Database::begin();
     Database::insert('game', array('id_user' => $this->user, 'pick_time' => isset($data['pick_time']) ? $data['pick_time'] : 0, 'pause_time' => isset($data['pause_time']) ? $data['pause_time'] : 0, 'type' => isset($data['type']) ? $data['type'] : 1, 'start' => $start));
     $id_game = Database::last_id();
     $order = 0;
     foreach ($sets as $set) {
         Database::insert('game_set', array('id_game' => $id_game, 'order' => ++$order, 'id_set' => $set['id']));
     }
     Database::commit();
     return array('success' => true);
 }
 public function process(array $documents, &$context)
 {
     $document = $documents[self::URL_MEDIA];
     $dom = self::getDOM($document);
     $xpath = new DOMXPath($dom);
     Database::delete('mediarelation', ['media_id' => $context->media->id]);
     $data = [];
     foreach ($xpath->query('//table[@class=\'anime_detail_related_anime\']/tr') as $node) {
         $typeMal = strtolower(Strings::removeSpaces($node->childNodes[0]->textContent));
         $type = Strings::makeEnum($typeMal, ['adaptation' => MediaRelation::Adaptation, 'alternative setting' => MediaRelation::AlternativeSetting, 'alternative version' => MediaRelation::AlternativeVersion, 'character' => MediaRelation::Character, 'full story' => MediaRelation::FullStory, 'other' => MediaRelation::Other, 'parent story' => MediaRelation::ParentStory, 'prequel' => MediaRelation::Prequel, 'sequel' => MediaRelation::Sequel, 'side story' => MediaRelation::SideStory, 'spin-off' => MediaRelation::SpinOff, 'summary' => MediaRelation::Summary], null);
         if ($type === null) {
             throw new BadProcessorDocumentException($document, 'unknown relation type: ' . $typeMal);
         }
         $links = $node->childNodes[1]->getElementsByTagName('a');
         foreach ($links as $link) {
             $link = $link->getAttribute('href');
             if (preg_match('#^/(anime|manga)/([0-9]+)/#', $link, $matches)) {
                 $idMal = Strings::makeInteger($matches[2]);
                 if ($matches[1] === 'anime') {
                     $media = Media::Anime;
                 } elseif ($matches[1] === 'manga') {
                     $media = Media::Manga;
                 }
                 $data[] = ['media_id' => $context->media->id, 'mal_id' => $idMal, 'media' => $media, 'type' => $type];
             }
         }
     }
     Database::insert('mediarelation', $data);
     $context->relationData = $data;
 }
示例#25
0
文件: note.php 项目: 4otaku/draft
 protected function do_add($data)
 {
     if (empty($data['text'])) {
         return array('success' => false);
     }
     $user = $this->user;
     $room = $this->id;
     $text = $data['text'];
     if ($room > 0 && !Database::get_count('game_user', 'id_game = ? and id_user = ?', array($room, $user))) {
         return array('success' => false);
     }
     $replace = array('&' => '&amp', '"' => '&quot;', '<' => '&lt;', '>' => '&gt;', '\\' => '&#092;', "'" => '&apos;');
     $text = str_replace(array_keys($replace), array_values($replace), $text);
     $text = trim($text);
     $lines = explode("\n", $text);
     $first_line = array_shift($lines);
     if (!$first_line) {
         return array('success' => false);
     }
     if (preg_match('/^.{200}/ui', $first_line, $result)) {
         $header = $result[0];
     } elseif (!empty($lines)) {
         $header = $first_line;
     } else {
         $header = '';
     }
     Database::insert('note', array('id_game' => $room, 'id_user' => $user, 'text' => $text, 'header' => $header));
     return array('success' => true);
 }
示例#26
0
 /**
  * 保存一个配置,支持批量设置
  *
  * @param string/array $key 关键字
  * @param mixed $value 值
  * @param string $type 类型,长度32以内
  * @param boolean $auto_clear_cache 自动清除缓存
  * @return boolean
  */
 public function set($key, $value, $type = '', $auto_clear_cache = true)
 {
     $db = new Database($this->database);
     $type = (string) $type;
     try {
         if (is_array($key)) {
             # 批量设置
             $tr = $db->transaction();
             $tr->start();
             try {
                 # 先尝试删除旧数据
                 $db->where('type', $type)->and_where_open();
                 foreach ($key as $k) {
                     $db->or_where('key_md5', md5($k));
                 }
                 $db->and_where_close()->delete($this->tablename);
                 # 设置数据
                 foreach ($key as $i => $k) {
                     $data = array('type' => $type, 'key_md5' => md5($k), 'key_name' => $k, 'value' => $this->data_format($value[$i]));
                     $db->values($data);
                 }
                 $db->columns(array('type', 'key_md5', 'key_name', 'value'));
                 $db->insert($this->tablename);
                 $tr->commit();
                 if (is_array($this->config)) {
                     foreach ($key as $i => $k) {
                         $this->config[$type][$k] = $value[$i];
                     }
                 }
                 if ($auto_clear_cache) {
                     $this->clear_cache($type);
                 }
                 return true;
             } catch (Exception $e) {
                 $tr->rollback();
                 return false;
             }
         } else {
             $data = array('type' => $type, 'key_md5' => md5($key), 'key_name' => $key, 'value' => $this->data_format($value));
             $status = $db->replace($this->tablename, $data);
             $status = $status[1];
             if ($status) {
                 if (is_array($this->config)) {
                     $this->config[$type][$key] = $value;
                 }
                 if ($auto_clear_cache) {
                     $this->clear_cache($type);
                 }
                 return true;
             } else {
                 return false;
             }
         }
     } catch (Exception $e) {
         if (IS_DEBUG) {
             throw $e;
         }
         return false;
     }
 }
示例#27
0
    public function add($id_host, $concepto)
    {
        include_once '../db.php';
        $db = new Database();
        $db->connect();
        $valores = array();
        $valores[0] = '"' . $concepto . '"';
        $valores[1] = 0;
        $valores[2] = 360;
        $valores[3] = '"' . date('Y-m-d') . '"';
        $valores[4] = 360;
        $valores[5] = 1;
        $valores[6] = '"pepe"';
        $valores[7] = 1;
        $valores[8] = $id_host;
        $idCreated = $db->insert('pagos', $valores, 'concepto,moneda,monto,fecha,pesos,tipo_op,editor,activo,id_host');
        $this->updateVencimiento($id_host, 1);
        $htm = '<li id="rowNro' . $idCreated . '" class="row rowAdded">
					<span class="col1">' . date('d-m-Y') . '</span>
					<span class="col2">' . $concepto . '</span>
					<span class="col3 tipo_op1">£ 360</span>
					<span class="col4">
						<a class="modifyOpTable disabledOp" href="javascript:;">&nbsp;</a>
						<a class="deleteOpTable" href="javascript:;" onClick="editarHosts(\'del\',' . $idCreated . ',\'' . str_replace("'", "\\'", $concepto) . '\',\'' . $id_host . '\')">&nbsp;</a>
					</span>
				</li>';
        return $htm;
    }
示例#28
0
 /**
  * add TestCategory in the database if name doesn't already exists
  */
 public function addCategoryInBDD()
 {
     $table = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
     $v_name = $this->name;
     $v_name = Database::escape_string($v_name);
     $v_description = $this->description;
     $v_description = Database::escape_string($v_description);
     // check if name already exists
     $sql = "SELECT count(*) AS nb FROM {$table}\n                WHERE title = '{$v_name}' AND c_id=" . api_get_course_int_id();
     $result_verif = Database::query($sql);
     $data_verif = Database::fetch_array($result_verif);
     // lets add in BDD if not the same name
     if ($data_verif['nb'] <= 0) {
         $c_id = api_get_course_int_id();
         $params = ['c_id' => $c_id, 'title' => $v_name, 'description' => $v_description];
         $new_id = Database::insert($table, $params);
         if ($new_id) {
             $sql = "UPDATE {$table} SET id = iid WHERE iid = {$new_id}";
             Database::query($sql);
             // add test_category in item_property table
             $course_id = api_get_course_int_id();
             $course_info = api_get_course_info_by_id($course_id);
             api_item_property_update($course_info, TOOL_TEST_CATEGORY, $new_id, 'TestCategoryAdded', api_get_user_id());
         }
         return $new_id;
     } else {
         return false;
     }
 }
示例#29
0
 public function register($name, $password, $password2, $email)
 {
     if ($password != $password2) {
         throw new UserError('Heslo sa nezhoduje.');
     }
     //overenie spravneho tvaru hesla
     $validation = new Validation();
     $validation->checkPasswordLength($password);
     //aktualny cas
     $date = new DateTime();
     $time = $date->getTimestamp();
     //activation key
     $key = md5(uniqid(rand(), true));
     //data pre DB
     $user = array('name' => $name, 'password' => $this->returnHash($password), 'registration_date' => $time, 'last_visit' => $time, 'email' => $email, 'activation_key' => $key);
     //vlozenie dat do DB
     try {
         Database::insert('users', $user);
     } catch (PDOException $error) {
         throw new UserError('Zadané meno alebo email sa už používa');
     }
     //odoslanie aktivacneho emailu
     try {
         $emailSender = new EmailSender();
         $message = 'Dobrý deň,<br><br>';
         $message .= 'pre dokončenie Vašej registrácie na stránke www.tomasblazy.com kliknite na nasledujúci link:<br><br>';
         $message .= 'www.tomasblazy.com/registracia/' . $name . '/' . $key . '<br><br>';
         $message .= 'V prípade, že ste o žiadnu registráciu nežiadali, tento email ignorujte.<br><br>';
         $message .= 'Ďakujeme<br><br>Tím CodingBlog<br><a href="http://tomasblazy.com">tomasblazy.com</a>';
         $emailSender->send($email, 'Aktivácia účtu na Coding Blog', $message, 'CodingBlog', '*****@*****.**');
     } catch (PDOException $error) {
         throw new UserError($error->getMessage(), 'warning');
     }
 }
示例#30
0
文件: abstract.php 项目: 4otaku/draft
 protected function insert_game_steps($sets)
 {
     if (Database::get_count('game_step', 'id_game = ? and type = ?', array($this->get_id(), 'build'))) {
         // Какой-то процесс успел раньше нас, откатываемся.
         throw new Error();
     }
     Database::insert('game_step', array('id_game' => $this->get_id(), 'type' => 'build', 'time' => date('Y-m-d G:i:s', time() + 864000)));
 }