function myquery($query) { global $time_mysql_query; global $numsql; global $debuginfo; $backtrace = debug_backtrace(); $back1 = $backtrace; $backtrace = " in : " . $backtrace[0]["file"] . ", on line: " . $backtrace[0]["line"] . ""; if (debug_run == 1) { $MyTimerSQL = new Timer(); $MyTimerSQL->Init(); //$result = mysql_query($query) or trigger_error(mysql_errno() . ": <b>" . mysql_error() . $backtrace . format_query($query) , E_USER_ERROR); $result = mysql_query($query) or send_error(mysql_errno() . ": <b>" . mysql_error() . $backtrace . "<br /><br /><p>Query: " . $query . "</p>", $backtrace); $exec_time_mysql = $MyTimerSQL->GetTime(5); $GLOBALS['numsql']++; $time_mysql_query += $exec_time_mysql; $GLOBALS['debuginfo'] .= '<tr><td>' . $query . '</td><td><span style="color:#C0FFFF">' . $exec_time_mysql . '</span></td><td><span style="color:lightgrey">' . $backtrace . '</span></tr>'; if (isset($GLOBALS['debug'][$back1[0]['file']])) { $GLOBALS['debug'][$back1[0]['file']]['time_sql'] += $exec_time_mysql; $GLOBALS['debug'][$back1[0]['file']]['count_sql'] += 1; } } else { $result = mysql_query($query); } /* if (strpos($query,"EXP")!==FALSE AND strpos($query,"game_users")!==FALSE AND strpos($query,"UPDATE")!==FALSE) { mysql_query("INSERT INTO query_log (query,timestamp,filename) VALUES ('$query',".time().",'$backtrace')"); } */ return $result; }
function myquery($query) { $backtrace = debug_backtrace(); $back1 = $backtrace; $backtrace = " in : " . $backtrace[0]["file"] . ", on line: " . $backtrace[0]["line"] . ""; $result = mysql_query($query) or send_error(mysql_errno() . ": <b>" . mysql_error() . $backtrace . "<br /><br /><br />" . $query . ""); return $result; }
function check_user_exists($uname, $uemail) { $DB = new database_class(); $sql = "SELECT COUNT(id) as count FROM User_table WHERE user_name = '{$uname}' LIMIT 1;"; $retval = mysql_query($sql, $DB->db_conn); if (!$retval) { die("ERROR :" . mysql_error()); } while ($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { $count = $row['count']; } if ($count == 1) { $mgs = "USER ALREADY EXISTS"; send_error($mgs); // exit(); } else { return true; } }
function init_saml2_auth() { global $sessionmanager_url; $sm = new SessionManager($sessionmanager_url); $ret = $sm->query('auth_params'); $dom = new DomDocument('1.0', 'utf-8'); $buf = @$dom->loadXML($ret); if (!$buf) { send_error("Unable to retrieve the SAML parameters"); } if (!$dom->hasChildNodes()) { send_error("Unable to retrieve the SAML parameters"); } $saml2 = $dom->getElementsByTagname('SAML2')->item(0); $url = $saml2->getElementsByTagname('idp_url')->item(0)->textContent; $fingerprint = $saml2->getElementsByTagname('idp_fingerprint')->item(0)->textContent; $cert = $saml2->getElementsByTagname('idp_cert')->item(0)->textContent; $settings = build_saml_settings($url, $fingerprint, $cert); return new OneLogin_Saml2_Auth($settings); }
$object = $class_to_call::load($id_to_load); $result = $object->{$method_to_call}($params); break; /* call the given normal method */ /* call the given normal method */ default: $object = new $class_to_call(); $result = $object->{$method_to_call}($params); } send_result($result); send_log('end of server process'); echo json_encode($global_result); } catch (Error $e) { if (!headers_sent()) { header('HTTP/1.0 ' . $e->http_code . ' ' . $e->http_status, TRUE, $e->http_code); } send_log('Backtrace: ' . $e->getTraceAsString()); send_error($e->getMessage()); echo json_encode($global_result); } catch (Exception $e) { if (!headers_sent()) { header('HTTP/1.0 500 Internal Server Error', TRUE, 500); header('Content-type: text/plain', TRUE); } echo 'Exception:' . TUNA_NEWLINE . $e->getMessage() . TUNA_NEWLINE . TUNA_NEWLINE; echo 'Code:' . TUNA_NEWLINE . $e->getCode() . TUNA_NEWLINE . TUNA_NEWLINE; echo 'Line:' . TUNA_NEWLINE . $e->getLine() . TUNA_NEWLINE . TUNA_NEWLINE; echo 'Backtrace:' . TUNA_NEWLINE . $e->getTraceAsString() . TUNA_NEWLINE . TUNA_NEWLINE; echo 'Request vars:' . TUNA_NEWLINE . print_r($_REQUEST, TRUE); } closelog();
function do_trackback($formatter, $options) { global $DBInfo, $_release; $entry = ''; if (!$formatter->page->exists()) { $pos = strrpos($formatter->page->name, '/'); if ($pos > 0) { $entry = substr($formatter->page->name, $pos + 1); $pagename = substr($formatter->page->name, 0, $pos); $page = new WikiPage($pagename); $formatter = new Formatter($page, $options); $options['page'] = $pagename; } else { $options['msg'] = _("Error: Page Not found !"); send_error(1, $options['msg']); } } if (empty($options['url'])) { $anchor = ''; if ($options['value']) { $anchor = '/' . $options['value']; } $formatter->send_header("", $options); if ($DBInfo->use_trackback) { $ping_url = qualifiedUrl($formatter->link_url($formatter->page->urlname . $anchor, "?action=trackback")); } else { $ping_url = _("TrackBack is not activated !"); } $sendping_action = $formatter->link_tag($formatter->page->urlname, "?action=sendping&value={$options['value']}", _("send ping")); $tb_cache = new Cache_text('trackback'); if ($tb_cache->exists($options['page'])) { $formatter->send_title(sprintf(_("TrackBack list of %s"), $options['page']), "", $options); $trackbacks = explode("\n", $tb_cache->fetch($options['page'])); unset($trackbacks[sizeof($trackbacks) - 1]); # trim the last empty line print "<div class='trackback-hint'><b>" . _("TrackBack URL for this page:") . "</b><br />\n{$ping_url}<br /><br />\n"; print "<b>" . _("Send TrackBack Ping to another Blog:") . "</b> {$sendping_action}</div>\n<br />"; foreach ($trackbacks as $trackback) { list($dummy, $entry, $url, $date, $sitename, $title, $excerpt) = explode("\t", $trackback); if ($anchor and '/' . $entry != $anchor) { continue; } $date[10] = " "; # 2003-07-11T12:08:33+09:00 # $time=strtotime($date); $time = strtotime($date); $date = date("@ m-d [h:i a]", $time); print "<div class='blog'>\n"; print "<div class='blog-title'><a href='{$url}'>{$title}</a></div>\n"; print "<div class='blog-user'>Submitted by <a href='{$url}'>{$sitename}</a> {$date}</div>\n"; print "<div class='blog-comment'>{$excerpt}</div>\n</div><br />\n"; } } else { $formatter->send_title(sprintf(_("No TrackBack entry found for %s"), $options['page']), "", $options); print "<div class='trackback-hint'><b>" . _("TrackBack URL for this page:") . "</b><br />\n{$ping_url}<br /><br />\n"; print "<b>" . _("Send TrackBack Ping to another Blog:") . "</b> {$sendping_action}</div>\n"; } $formatter->send_footer("", $options); return; } if (!$DBInfo->use_trackback) { send_error(1, "TrackBack is not enabled"); } if (empty($options['title']) or empty($options['excerpt']) or empty($options['blog_name']) or empty($options['url'])) { send_error(1, "Invalid TrackBack Ping"); } # receivie Trackback ping # strip \n $title = strtr(_stripslashes($options['title']), "\t\n", " \r"); $excerpt = strtr(_stripslashes($options['excerpt']), "\t\n", " \r"); $blog_name = strtr(_stripslashes($options['blog_name']), "\t\n", " \r"); $url = strtr(_stripslashes($options['url']), "\t\n", " \r"); $timestamp = time(); $date = gmdate("Y-m-d\\TH:i:s", $timestamp); $receive = $timestamp . "\t" . $entry . "\t" . $url . "\t" . $date . "\t" . $blog_name . "\t" . $title . "\t" . $excerpt . "\n"; $tb_cache = new Cache_text('trackback'); $old = $tb_cache->fetch($options['page']); $ret = $tb_cache->update($options['page'], $old . $receive, time()); if ($ret === false) { send_error(0, "Can't update Trackback list. Please try again"); } send_error(0, 'Successfully added'); }
function handle_paypal_ipn() { ob_end_clean(); if (!isset($_REQUEST['custom'])) { return; } $paypal_bits = explode("|", $_REQUEST['custom']); $user_id = (int) $paypal_bits[0]; $payment_id = (int) $paypal_bits[1]; $invoice_id = (int) $paypal_bits[2]; $invoice_payment_subscription_id = false; if (count($paypal_bits) == 4) { // normal IPN, single payment. } else { if (count($paypal_bits) == 5) { // subscription IPN, with subscription id. $invoice_payment_subscription_id = (int) $paypal_bits[3]; $invoice_payment_subscription = get_single('invoice_payment_subscription', 'invoice_payment_subscription_id', $invoice_payment_subscription_id); } } //send_error('bad?'); if ($payment_id && $invoice_id) { $hash = $this->paypal_custom($user_id, $payment_id, $invoice_id, $invoice_payment_subscription_id); if ($hash != $_REQUEST['custom']) { send_error("PayPal IPN Error (incorrect hash) it should be " . $hash); exit; } /*$sql = "SELECT * FROM `"._DB_PREFIX."user` WHERE user_id = '$user_id' LIMIT 1"; $res = qa($sql); if($res){ $user = array_shift($res); if($user && $user['user_id'] == $user_id){*/ // check for payment exists $payment = module_invoice::get_invoice_payment($payment_id); $invoice = module_invoice::get_invoice($invoice_id); if ($payment && $invoice) { /*if(isset($_REQUEST['fakepay'])){ if($invoice_payment_subscription_id){ // we have a subscription payment. woo! // this gets a bit tricky, we have to work out if the invoice has been generated for this subscription yet. // if this invoice hasn't been generated yet then we have to generate it. // pass this back to the invoice class so we can reuse this feature in the future. $data = module_invoice::create_new_invoice_for_subscription_payment($invoice_id, $payment_id, $invoice_payment_subscription_id); if($data && $data['invoice_id'] && $data['invoice_payment_id']){ $next_time = time(); $next_time = strtotime('+'.abs((int)$invoice_payment_subscription['days']).' days',$next_time); $next_time = strtotime('+'.abs((int)$invoice_payment_subscription['months']).' months',$next_time); $next_time = strtotime('+'.abs((int)$invoice_payment_subscription['years']).' years',$next_time); update_insert('invoice_payment_subscription_id',$invoice_payment_subscription_id,'invoice_payment_subscription',array( 'date_last_pay' => date('Y-m-d'), 'date_next' => date('Y-m-d',$next_time), )); $new_payment_details = array( 'date_paid' => date('Y-m-d'), 'amount' => $_REQUEST['mc_gross'], 'method' => 'PayPal (Subscription)', 'invoice_payment_subscription_id' => $invoice_payment_subscription_id, ); foreach(array('fee_percent','fee_amount','fee_description','fee_total') as $fee_field){ if(isset($payment[$fee_field])) { $new_payment_details[ $fee_field ] = $payment[ $fee_field ]; } } update_insert("invoice_payment_id",$data['invoice_payment_id'],"invoice_payment",$new_payment_details); module_invoice::save_invoice($data['invoice_id'],array()); echo "Successful Subscription Payment!"; }else{ send_error("PayPal IPN Subscription Error (failed to generate new invoice!) ".var_export($result,true)); } }else{ // mark a normal payment as paid update_insert("invoice_payment_id",$payment_id,"invoice_payment",array( 'date_paid' => date('Y-m-d'), 'amount' => $_REQUEST['mc_gross'], 'method' => 'PayPal (IPN)', )); module_invoice::save_invoice($invoice_id,array()); echo "Successful Payment!"; } echo 'fakepay done';exit; }*/ $invoice_currency = module_config::get_currency($invoice['currency_id']); $invoice_currency_code = $invoice_currency['code']; // check correct business if (!$_REQUEST['business'] && $_REQUEST['receiver_email']) { $_REQUEST['business'] = $_REQUEST['receiver_email']; } if ($_REQUEST['business'] != module_config::c('payment_method_paypal_email', _ERROR_EMAIL)) { send_error('PayPal error! Paid the wrong business name. ' . $_REQUEST['business'] . ' instead of ' . module_config::c('payment_method_paypal_email', _ERROR_EMAIL)); exit; } // check correct currency if ($invoice_currency_code && $_REQUEST['mc_currency'] != $invoice_currency_code) { send_error('PayPal error! Paid the wrong currency code. ' . $_REQUEST['mc_currency'] . ' instead of ' . $invoice_currency_code); exit; } switch ($_REQUEST['txn_type']) { // handle subscriptions first. // https://www.paypal.com/au/cgi-bin/webscr?cmd=p/acc/ipn-subscriptions-outside case "subscr_signup": // started! we update the start date of this one. if ($invoice_payment_subscription_id) { update_insert('invoice_payment_subscription_id', $invoice_payment_subscription_id, 'invoice_payment_subscription', array('status' => _INVOICE_SUBSCRIPTION_ACTIVE, 'date_start' => date('Y-m-d'))); } break; case "subscr_cancel": case "subscr_failed": case "subscr_eot": if ($invoice_payment_subscription_id) { update_insert('invoice_payment_subscription_id', $invoice_payment_subscription_id, 'invoice_payment_subscription', array('status' => _INVOICE_SUBSCRIPTION_FAILED)); } break; break; case "subscr_payment": case "web_accept": if ($_REQUEST['payment_status'] == "Canceled_Reversal" || $_REQUEST['payment_status'] == "Refunded") { // funky refund!! oh noes!! // TODO: store this in the database as a negative payment... should be easy. // populate $_REQUEST vars then do something like $payment_history_id = update_insert("payment_history_id","new","payment_history"); send_error("PayPal Error! The payment {$payment_id} has been refunded or reversed! BAD BAD! You have to follup up customer for money manually now."); } else { if ($_REQUEST['payment_status'] == "Completed") { // payment is completed! yeye getting closer... // running in paypal sandbox or not? //$sandbox = (self::is_sandbox())?"sandbox.":''; // quick check we're not getting a fake payment request. $url = 'https://www.' . (self::is_sandbox() ? 'sandbox.' : '') . 'paypal.com/cgi-bin/webscr'; $result = self::fsockPost($url, $_POST); //send_error('paypal sock post: '.$url."\n\n".var_export($result,true)); if (eregi("VERIFIED", $result)) { // finally have everything. // mark the payment as completed. if ($invoice_payment_subscription_id) { // we have a subscription payment. woo! // this gets a bit tricky, we have to work out if the invoice has been generated for this subscription yet. // if this invoice hasn't been generated yet then we have to generate it. // pass this back to the invoice class so we can reuse this feature in the future. $data = module_invoice::create_new_invoice_for_subscription_payment($invoice_id, $payment_id, $invoice_payment_subscription_id); if ($data && $data['invoice_id'] && $data['invoice_payment_id']) { $next_time = time(); $next_time = strtotime('+' . abs((int) $invoice_payment_subscription['days']) . ' days', $next_time); $next_time = strtotime('+' . abs((int) $invoice_payment_subscription['months']) . ' months', $next_time); $next_time = strtotime('+' . abs((int) $invoice_payment_subscription['years']) . ' years', $next_time); update_insert('invoice_payment_subscription_id', $invoice_payment_subscription_id, 'invoice_payment_subscription', array('date_last_pay' => date('Y-m-d'), 'date_next' => date('Y-m-d', $next_time))); $new_payment_details = array('date_paid' => date('Y-m-d'), 'amount' => $_REQUEST['mc_gross'], 'method' => 'PayPal (Subscription)', 'invoice_payment_subscription_id' => $invoice_payment_subscription_id); foreach (array('fee_percent', 'fee_amount', 'fee_description', 'fee_total') as $fee_field) { if (isset($payment[$fee_field])) { $new_payment_details[$fee_field] = $payment[$fee_field]; } } update_insert("invoice_payment_id", $data['invoice_payment_id'], "invoice_payment", $new_payment_details); module_invoice::save_invoice($data['invoice_id'], array()); echo "Successful Subscription Payment!"; } else { send_error("PayPal IPN Subscription Error (failed to generate new invoice!) " . var_export($result, true)); } } else { // mark a normal payment as paid update_insert("invoice_payment_id", $payment_id, "invoice_payment", array('date_paid' => date('Y-m-d'), 'amount' => $_REQUEST['mc_gross'], 'method' => 'PayPal (IPN)')); module_invoice::save_invoice($invoice_id, array()); echo "Successful Payment!"; } /*// send customer an email thanking them for their payment. $sql = "SELECT * FROM "._DB_PREFIX."users WHERE user_id = '"._ADMIN_USER_ID."'"; $res = qa($sql); $admin = array_shift($res); $from_email = $admin['email']; $from_name = $admin['real_name']; $mail_content = "Dear ".$user['real_name'].", \n\n"; $mail_content .= "Your ".dollar($payment['outstanding'])." payment for '".$payment['description']."' has been processed. \n\n"; $mail_content .= "We have successfully recorded your ".dollar($_REQUEST['mc_gross'])." payment in our system.\n\n"; $mail_content .= "You will receive another email shortly from PayPal with details of the transaction.\n\n"; $mail_content .= "Kind Regards,\n\n"; $mail_content .= $from_name."\n".$from_email; send_error("PayPal SUCCESS!! User has paid you ".$_REQUEST['mc_gross']." we have recorded this against the payment and sent them an email"); //$this->send_email( $payment_id, $user['email'], $mail_content, "Payment Successful", $from_email, $from_name ); send_email($user['email'], "Payment Successful", $mail_content, array("FROM"=>$from_email,"FROM_NAME"=>$from_name)); */ // check if it's been paid in full.. } else { send_error("PayPal IPN Error (paypal rejected the payment!) " . var_export($result, true)); } } else { send_error("PayPal info: This payment is not yet completed, this usually means it's an e-cheque, follow it up in a few days if you dont hear anything. This also means you may have to login to paypal and 'Accept' the payment. So check there first."); } } break; default: send_error("PayPal IPN Error (unknown transaction t ype!) "); break; } } else { send_error("PayPal IPN Error (no payment found in database!)"); } /*}else{ send_error("PayPal IPN Error (error with user that was found in database..)"); } }else{ send_error("PayPal IPN Error (no user found in database #1)"); }*/ } else { send_error("PayPal IPN Error (no payment or invoice id found)"); } exit; }
* as published by the Free Software Foundation; version 2 * of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ require_once dirname(__FILE__) . '/common.inc.php'; try { $auth = init_saml2_auth(); $auth->processResponse(); } catch (Exception $e) { send_error($e->getMessage()); } $errors = $auth->getErrors(); if (!empty($errors)) { send_error(implode(', ', $errors)); } if (!$auth->isAuthenticated()) { send_error("Not authenticated"); } $_SESSION['SAML2'] = true; $_SESSION['SAML2_login'] = $auth->getNameId(); $_SESSION['SAML2_ticket'] = $_POST['SAMLResponse']; setcookie('ovd-sso', 'true', 0, '/ovd/'); $auth->redirectTo(SAML2_REDIRECT_URI . '/ovd/');
function resize_images() { global $xoopsUser, $xoopsLogger, $xoopsSecurity; set_time_limit(0); error_reporting(0); $xoopsLogger->activated = false; $params = rmc_server_var($_GET, 'data', ''); $id = rmc_server_var($_GET, 'img', 0); if ($params == '') { send_error(__('Unauthorized!', 'rmcommon')); } if ($id <= 0) { send_error(__('Invalid image!', 'rmcommon')); } $params = TextCleaner::decrypt($params); $data = explode('|', $params); if ($data[0] != $xoopsUser->uid()) { send_error(__('Unauthorized!', 'rmcommon')); } if ($data[1] != RMCURL . '/images.php') { send_error(__('Unauthorized!', 'rmcommon')); } if (!$xoopsSecurity->check(false, $data[2])) { send_error(__('Unauthorized!', 'rmcommon')); } $image = new RMImage($id); if ($image->isNew()) { send_error(__('Image not found!', 'rmcommon')); } // Resize image $cat = new RMImageCategory($image->getVar('cat')); if (!$cat->user_allowed_toupload($xoopsUser)) { send_error(__('Unauthorized', 'rmcommon')); } $sizes = $cat->getVar('sizes'); $updir = XOOPS_UPLOAD_PATH . '/' . date('Y', $image->getVar('date')) . '/' . date('m', time()); $upurl = XOOPS_UPLOAD_URL . '/' . date('Y', $image->getVar('date')) . '/' . date('m', time()); $width = 0; $tfile = ''; foreach ($sizes as $size) { if ($size['width'] <= 0 && $size['height'] <= 0) { continue; } $fd = pathinfo($updir . '/' . $image->getVar('file')); $name = $updir . '/sizes/' . $fd['filename'] . '_' . $size['width'] . 'x' . $size['height'] . '.' . $fd['extension']; $sizer = new RMImageResizer($updir . '/' . $image->getVar('file'), $name); switch ($size['type']) { case 'crop': $sizer->resizeAndCrop($size['width'], $size['height']); break; default: if ($size['width'] <= 0 || $size['height'] <= 0) { $sizer->resizeWidth($size['width']); } else { $sizer->resizeWidthOrHeight($size['width'], $size['height']); } break; } if ($size['width'] <= $width || $width == 0) { $width = $size['width']; $tfile = str_replace(XOOPS_UPLOAD_PATH, XOOPS_UPLOAD_URL, $name); } } $ret['message'] = sprintf(__('%s done!', 'rmcommon'), $image->getVar('file')); $ret['done'] = 1; $ret['file'] = $tfile; $ret['title'] = $image->getVar('title'); echo json_encode($ret); die; }
public function get_list() { global $user; if ($this->cleanfile) { $table = $this->vars_table_cleanfiles; $root_path = $this->vars_cleanfiles_root; } else { $table = $this->vars_table_samples; $root_path = $this->vars_dirty_root; } // Configure to collect files from local storage using the preferred hash if ($this->cleanfile) { $type = 'Clean'; $res = $this->sql->query("SELECT md5_scl as md5, file_size_scl 'size' FROM {$table} WHERE " . $this->virex_ExtraConditions['clean'] . ' GROUP BY md5_scl'); } else { $type = 'Detected'; $res = $this->sql->query("SELECT md5_sde as md5, file_size_sde 'size' FROM {$table} WHERE " . $this->virex_ExtraConditions['detected'] . ' GROUP BY md5_sde'); } if (!$res) { $this->send_error($this->sql->error); } $plaintext = tempnam(VIREX_TEMP_PATH, "HashList"); $this->virex_register_list_download($res->num_rows, $type); $fout = fopen($plaintext, "w"); if (!$fout) { send_error("Unable to create {$plaintext}"); } if ($res) { while ($row = $res->fetch_object()) { if ($row->size > 0) { $hex = $this->ascii2hex($row->md5); if ($row->md5 == "") { continue; } $this->virex_add_file_to_list($row->md5, $row->size); $part1 = substr($hex, 0, 3); $part2 = substr($hex, 3, 3); $part3 = substr($hex, 6, 3); $file = $root_path . "/{$part1}/{$part2}/{$part3}/{$hex}"; if (!file_exists($file)) { continue; } fwrite($fout, "{$row->md5}:{$row->size}\r\n"); } } } fclose($fout); return $plaintext; }
include "../app/models/lesson_composition.php"; include "../app/models/video.php"; // NO ACTION PROVIDED if (!isset($_GET['action'])) { send_error(); } // ACTIONS, OUR CONTROLLER switch ($_GET['action']) { case 'loadcomposers': $composer = new Composer(); $data = $composer->loadComposers(); send_json($data); break; case 'getnextcomposition': $composition = new Composition(); $data = $composition->getNextComposition(); send_json($data); break; default: send_error(); } // AUXILIAR function send_error() { send_json(array('success' => false)); } function send_json($data) { header('Content-Type: application/json'); echo json_encode($data); }
send_error("authentication", $e); } catch (Stripe_ApiConnectionError $e) { send_error("network", $e); } catch (Stripe_Error $e) { send_error("generic", $e); } catch (Exception $e) { if ($e->getMessage() == "zip_check_invalid") { $smartyvalues["processingerror"] = 'Error: The address information on your account does not match that of the credit card you are trying to use. Please try again or contact us if the problem persists.'; } else { if ($e->getMessage() == "address_check_invalid") { $smartyvalues["processingerror"] = 'The address information on your account does not match that of the credit card you are trying to use. Please try again or contact us if the problem persists.'; } else { if ($e->getMessage() == "cvc_check_invalid") { $smartyvalues["processingerror"] = 'The credit card information you specified is not valid. Please try again or contact us if the problem persists.'; } else { send_error("unkown", $e); } } } } } // end of if to check if this is a token acceptance for recurs } } else { // User is logged in but they shouldn't be here (i.e. they weren't here from an invoice) header("Location: clientarea.php?action=details"); } } else { header("Location: index.php"); } # Define the template filename to be used without the .tpl extension
function apply_filter() { global $C, $I, $U, $db, $memcached; if ($U['poststatus'] !== 9 && preg_match('~^/me~i', $U['message'])) { $U['displaysend'] = substr($U['displaysend'], 0, -3); $U['message'] = preg_replace("~^/me~i", '', $U['message']); } $U['message'] = preg_replace_callback('/\\@([a-z0-9]{1,})/i', function ($matched) { global $A, $P; if (isset($P[$matched[1]])) { return style_this($matched[0], $P[$matched[1]][1]); } $nick = strtolower($matched[1]); foreach ($P as $user) { if (strtolower($user[0]) === $nick) { return style_this($matched[0], $user[1]); } } read_members(); if (isset($A[$matched[1]])) { return style_this($matched[0], $A[$matched[1]][2]); } foreach ($A as $user) { if (strtolower($user[0]) === $nick) { return style_this($matched[0], $user[2]); } } return "{$matched['0']}"; }, $U['message']); if ($C['memcached']) { $filters = $memcached->get("{$C['dbname']}-{$C['prefix']}filter"); } if (!$C['memcached'] || $memcached->getResultCode() !== Memcached::RES_SUCCESS) { $filters = array(); $result = $db->query("SELECT id, filtermatch, filterreplace, allowinpm, regex, kick FROM {$C['prefix']}filter;"); while ($filter = $result->fetch(PDO::FETCH_ASSOC)) { $filters[] = array('id' => $filter['id'], 'match' => $filter['filtermatch'], 'replace' => $filter['filterreplace'], 'allowinpm' => $filter['allowinpm'], 'regex' => $filter['regex'], 'kick' => $filter['kick']); } if ($C['memcached']) { $memcached->set("{$C['dbname']}-{$C['prefix']}filter", $filters); } } foreach ($filters as $filter) { if ($U['poststatus'] !== 9) { $U['message'] = preg_replace("/{$filter['match']}/i", $filter['replace'], $U['message'], -1, $count); } elseif (!$filter['allowinpm']) { $U['message'] = preg_replace("/{$filter['match']}/i", $filter['replace'], $U['message'], -1, $count); } if (isset($count) && $count > 0 && $filter['kick']) { kick_chatter(array($U['nickname']), '', false); send_error("{$I['kicked']}"); } } }
public function external_hook($hook) { switch ($hook) { case 'event_ipn': require_once 'includes/plugin_paymethod_stripe/stripe-php/lib/Stripe.php'; $stripe = array("secret_key" => module_config::c('payment_method_stripe_secret_key'), "publishable_key" => module_config::c('payment_method_stripe_publishable_key')); Stripe::setApiKey($stripe['secret_key']); $body = @file_get_contents('php://input'); $event_json = json_decode($body); ob_start(); // echo "INPUT: <br>\n"; // print_r($body); // echo "<br><br>\n"; echo "UCM STRIPE DEBUG:<br><br>JSON: <br>\n"; print_r($event_json); echo "<br><br>\n"; $event_id = $event_json->id; try { $event = Stripe_Event::retrieve($event_id); // This will send receipts on succesful invoices if ($event->type == 'charge.succeeded' && $event->data->object->invoice) { $paid_amount = $event->data->object->amount / 100; // get the invoice. $invoice = Stripe_Invoice::retrieve($event->data->object->invoice); echo "INVOICE: <br>\n"; print_r($invoice); echo "<br><br>\n"; if ($invoice && $invoice->subscription && $invoice->paid) { // this payment was for a subscription! which one though? $customer = Stripe_Customer::retrieve($invoice->customer); echo "CUSTOMER: <br>\n"; print_r($customer); echo "<br><br>\n"; $subscription = $customer->subscriptions->retrieve($invoice->subscription); echo "SUBSCRIPTION: <br>\n"; print_r($subscription); echo "<br><br>\n"; // now we have the Customer and Subscription we can look through our invoice_payment_subscription table for those values. /*update_insert('invoice_payment_subscription_id',$invoice_payment_subscription_id,'invoice_payment_subscription',array( 'status' => _INVOICE_SUBSCRIPTION_ACTIVE, 'date_start' => date('Y-m-d'), // we also have to store the stripe details here so we can easily search for them later on. 'stripe_customer' => $stripe_customer->id, 'stripe_subscription' => $stripe_subscription->id, ));*/ $invoice_payment_subscription = get_single('invoice_payment_subscription', array('stripe_customer', 'stripe_subscription'), array($customer->id, $subscription->id)); if ($invoice_payment_subscription) { // FIND THE linked invoice_payment for this original invoice payment subscription, this allows us to perform the same creatE_new_invoice as paypal below: $invoice_payment_subscription_id = $invoice_payment_subscription['invoice_payment_subscription_id']; $invoice_payment = get_single('invoice_payment', 'invoice_payment_subscription_id', $invoice_payment_subscription_id); if ($invoice_payment) { $payment_id = $invoice_payment['invoice_payment_id']; $invoice_id = $invoice_payment['invoice_id']; // we have a subscription payment. woo! // this gets a bit tricky, we have to work out if the invoice has been generated for this subscription yet. // if this invoice hasn't been generated yet then we have to generate it. // pass this back to the invoice class so we can reuse this feature in the future. $data = module_invoice::create_new_invoice_for_subscription_payment($invoice_id, $payment_id, $invoice_payment_subscription_id); if ($data && $data['invoice_id'] && $data['invoice_payment_id']) { $next_time = time(); $next_time = strtotime('+' . abs((int) $invoice_payment_subscription['days']) . ' days', $next_time); $next_time = strtotime('+' . abs((int) $invoice_payment_subscription['months']) . ' months', $next_time); $next_time = strtotime('+' . abs((int) $invoice_payment_subscription['years']) . ' years', $next_time); update_insert('invoice_payment_subscription_id', $invoice_payment_subscription_id, 'invoice_payment_subscription', array('date_last_pay' => date('Y-m-d'), 'date_next' => date('Y-m-d', $next_time))); update_insert("invoice_payment_id", $data['invoice_payment_id'], "invoice_payment", array('date_paid' => date('Y-m-d'), 'amount' => $paid_amount, 'method' => 'Stripe (Subscription)', 'invoice_payment_subscription_id' => $invoice_payment_subscription_id)); module_paymethod_stripe::add_payment_data($data['invoice_payment_id'], 'log', "Payment Received via Webhook: " . var_export(array('event.type' => $event->type, 'invoice.id' => $invoice->id, 'subscription.id' => $subscription->id, 'customer.id' => $customer->id, '$invoice_payment_subscription_id' => $invoice_payment_subscription_id, '$invoice_payment_id' => $payment_id), true)); module_invoice::save_invoice($data['invoice_id'], array()); echo "Successful Subscription Payment For Invoice " . $data['invoice_id']; } else { send_error("Stripe Webhook Subscription Error (failed to generate new invoice!) " . var_export($data, true)); } } else { echo 'Failed to find matching invoice payment in db'; } } else { echo 'Failed to find matching subscription payment in db'; } } } } catch (Exception $e) { $body = $e->getJsonBody(); $err = $body['error']; $error = "Sorry: Webhook failed. <br><br>\n\n"; $error .= $err['message']; $error .= "\n\n\n" . var_export($e, true); echo $error; } $debug = ob_get_clean(); //mail('*****@*****.**','Stripe Webhook debug',$debug); if (module_config::c('stripe_payment_debug', 0)) { echo $debug; } echo "Thanks! (set stripe_payment_debug to 1 in UCM to see more data here)"; exit; break; case 'pay_subscription': $invoice_id = isset($_REQUEST['invoice_id']) ? $_REQUEST['invoice_id'] : false; $invoice_payment_id = isset($_REQUEST['invoice_payment_id']) ? $_REQUEST['invoice_payment_id'] : false; $invoice_payment_subscription_id = isset($_REQUEST['invoice_payment_subscription_id']) ? $_REQUEST['invoice_payment_subscription_id'] : false; $stripe_plan_id = isset($_REQUEST['stripe_plan_id']) ? $_REQUEST['stripe_plan_id'] : false; $user_id = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : false; if ($invoice_id && $invoice_payment_id && $stripe_plan_id && $invoice_payment_subscription_id && $user_id && isset($_POST['stripeToken'])) { $user_data = module_user::get_user($user_id); $email = isset($_REQUEST['stripeEmail']) && strlen($_REQUEST['stripeEmail']) ? $_REQUEST['stripeEmail'] : $user_data['email']; if (!$email || !strpos($email, '@')) { die('Please ensure your user account has a valid email address before paying with stripe'); } $invoice_payment = get_single('invoice_payment', 'invoice_payment_id', $invoice_payment_id); $invoice_payment_subscription = get_single('invoice_payment_subscription', 'invoice_payment_subscription_id', $invoice_payment_subscription_id); if (!$invoice_payment || !$invoice_payment_subscription || $invoice_payment['invoice_id'] != $invoice_id || $invoice_payment['invoice_payment_subscription_id'] != $invoice_payment_subscription_id) { die('Invalid invoice payment subscription id'); } $invoice_payment_data = module_invoice::get_invoice_payment($invoice_payment_id); $invoice_data = module_invoice::get_invoice($invoice_id); if ($invoice_payment_data && $invoice_data && $invoice_id == $invoice_data['invoice_id'] && $invoice_payment_data['invoice_id'] == $invoice_data['invoice_id']) { $currency = module_config::get_currency($invoice_payment_data['currency_id']); $currency_code = $currency['code']; $description = isset($_REQUEST['description']) ? $_REQUEST['description'] : 'N/A'; $template = new module_template(); ob_start(); require_once 'includes/plugin_paymethod_stripe/stripe-php/lib/Stripe.php'; $stripe = array("secret_key" => module_config::c('payment_method_stripe_secret_key'), "publishable_key" => module_config::c('payment_method_stripe_publishable_key')); Stripe::setApiKey($stripe['secret_key']); try { // todo- search for existing customer based on email address??? // todo: check if adding new plan to existing customer work?? $stripe_customer = Stripe_Customer::create(array("card" => $_POST['stripeToken'], "email" => $email, 'metadata' => array('user_id' => $user_id))); if ($stripe_customer && $stripe_customer->id) { //} && $stripe_customer->subscriptions){ $stripe_subscription = $stripe_customer->subscriptions->create(array('plan' => $stripe_plan_id)); if ($stripe_subscription && $stripe_subscription->id) { update_insert('invoice_payment_subscription_id', $invoice_payment_subscription_id, 'invoice_payment_subscription', array('status' => _INVOICE_SUBSCRIPTION_ACTIVE, 'date_start' => date('Y-m-d'), 'stripe_customer' => $stripe_customer->id, 'stripe_subscription' => $stripe_subscription->id)); module_paymethod_stripe::add_payment_data($invoice_payment_id, 'log', "Started Stripe Subscription: " . var_export(array('customer.id' => $stripe_customer->id, 'plan.id' => $stripe_plan_id, 'subscription.id' => $stripe_subscription->id), true)); // success! // redirect to receipt page. redirect_browser(module_invoice::link_public_payment_complete($invoice_id)); } else { echo 'Failed to create subscription with stripe'; } } $error = "Something went wrong during stripe payment. Please confirm invoice payment went through: " . htmlspecialchars($description); send_error($error); echo $error; } catch (Stripe_CardError $e) { // The card has been declined $body = $e->getJsonBody(); $err = $body['error']; $error = "Sorry: Payment failed. <br><br>\n\n" . htmlspecialchars($description) . ". <br><br>\n\n"; $error .= $err['message']; echo $error; $error .= "\n\n\n" . var_export($err, true); send_error($error); } catch (Exception $e) { $body = $e->getJsonBody(); $err = $body['error']; $error = "Sorry: Payment failed. <br><br>\n\n" . htmlspecialchars($description) . ". <br><br>\n\n"; $error .= $err['message']; echo $error; $error .= "\n\n\n" . var_export($err, true); send_error($error); } $template->content = ob_get_clean(); echo $template->render('pretty_html'); exit; } } echo 'Error paying via Stripe'; exit; case 'pay': $invoice_id = isset($_REQUEST['invoice_id']) ? $_REQUEST['invoice_id'] : false; $invoice_payment_id = isset($_REQUEST['invoice_payment_id']) ? $_REQUEST['invoice_payment_id'] : false; if ($invoice_id && $invoice_payment_id && isset($_POST['stripeToken'])) { $invoice_payment_data = module_invoice::get_invoice_payment($invoice_payment_id); $invoice_data = module_invoice::get_invoice($invoice_id); if ($invoice_payment_data && $invoice_data && $invoice_id == $invoice_data['invoice_id'] && $invoice_payment_data['invoice_id'] == $invoice_data['invoice_id']) { $currency = module_config::get_currency($invoice_payment_data['currency_id']); $currency_code = $currency['code']; $description = _l('Payment for invoice %s', $invoice_data['name']); $template = new module_template(); ob_start(); include module_theme::include_ucm('includes/plugin_paymethod_stripe/pages/stripe_form.php'); $template->content = ob_get_clean(); echo $template->render('pretty_html'); exit; } } echo 'Error paying via Stripe'; exit; } }
/** * @desc Almacena la información del grupo de imágenes **/ function saveBulkImages() { global $util, $mc, $xoopsUser; XoopsLogger::getInstance()->activated = false; XoopsLogger::getInstance()->renderingEnabled = false; set_time_limit(0); foreach ($_POST as $k => $v) { ${$k} = $v; } $ruta = "page={$page}&search={$search}&owner={$uid}&sort={$sort}&mode={$mode}"; if ($xoopsUser->uid() == $uid) { $xu = $xoopsUser; } else { $xu = new XoopsUser($uid); } //Verificamos si el usuario se encuentra registrado $user = new GSUser($xu->uname()); if ($user->isNew()) { //Insertamos información del usuario $user->setUid($uid); $user->setUname($xu->uname()); $user->setQuota($mc['quota'] * 1024 * 1024); $user->setDate(time()); if (!$user->save()) { send_error(__('User owner could not be created!', 'galleries') . "<br />" . $user->errors()); die; } else { mkdir($mc['storedir'] . "/" . $user->uname()); mkdir($mc['storedir'] . "/" . $user->uname() . "/ths"); mkdir($mc['storedir'] . "/" . $user->uname() . "/formats"); } } else { @mkdir($mc['storedir'] . "/" . $user->uname()); @mkdir($mc['storedir'] . "/" . $user->uname() . "/ths"); @mkdir($mc['storedir'] . "/" . $user->uname() . "/formats"); } // Insertamos las etiquetas $tgs = explode(",", $tags); /** * @desc Almacena los ids de las etiquetas que se asignarán a la imágen */ $ret = array(); foreach ($tgs as $k) { $k = trim($k); if ($k == '') { continue; } // Comprobamos que la palabra tenga la longitud permitida if (strlen($k) < $mc['min_tag'] || strlen($k) > $mc['max_tag']) { continue; } // Creamos la etiqueta $tag = new GSTag($k); if (!$tag->isNew()) { // Si ya existe nos saltamos $ret[] = $tag->id(); continue; } $tag->setTag($k); if ($tag->save()) { $ret[] = $tag->id(); } } $errors = ''; $k = 1; include_once RMCPATH . '/class/uploader.php'; $updir = $mc['storedir'] . "/" . $xu->uname(); $upths = $mc['storedir'] . "/" . $xu->uname() . "/ths"; // Cargamos la imágen if (!file_exists($updir)) { mkdir($updir, 511); } if (!file_exists($upths)) { mkdir($upths, 511); } $uploader = new RMFileUploader($updir, $mc['size_image'] * 1024, array('gif', 'jpg', 'jpeg', 'png')); $err = array(); if (!$uploader->fetchMedia('Filedata')) { send_error($uploader->getErrors()); } if (!$uploader->upload()) { send_error($uploader->getErrors()); } // Insertamos el archivo en la base de datos $img = new GSImage(); $img->setTitle($uploader->savedFileName); $img->setOwner($uid); $img->setPublic(2); $img->setCreated(time()); $img->setImage($uploader->getSavedFileName()); if (!$image->save()) { unlink($uploader->savedDestination); send_error(__('File could not be inserted to database!', 'galleries')); } $ret['message'] = '1'; $ret['id'] = $image->id(); echo json_encode($ret); die; }
<?php //sleep(1); $will_fail = isset($_GET['f']) ? $_GET['f'] : false; $item_id = isset($_GET['id']) ? $_GET['id'] : null; if ($will_fail == 'php') { header("HTTP/1.0 500 Application Error"); trigger_error("THIS IS A TEST ERROR MESSAGE", E_USER_ERROR); return; } if ($will_fail == 'r') { // randomly fail or succeed $will_fail = mt_rand() % 2 == 0 ? 'y' : 'n'; } if ($will_fail == 'y') { send_error(601, "could not save for id: '{$item_id}'"); } else { send_result(200, "item_id '{$item_id}' saved!"); } function send_error($code, $message) { header("HTTP/1.0 500 Application Error"); send_result($code, $message); } function send_result($code, $message) { header('Content-type: application/json'); print json_encode(array('code' => $code, 'message' => $message)); }
/** * Resize images */ function gs_resize_images() { global $xoopsUser, $xoopsLogger, $xoopsSecurity; set_time_limit(0); $mc = RMUtilities::module_config('galleries'); $params = rmc_server_var($_GET, 'data', ''); $id = rmc_server_var($_GET, 'img', 0); if ($params == '') { send_error(__('Unauthorized!', 'galleries')); } if ($id <= 0) { send_error(__('Invalid image!', 'galleries')); } $params = TextCleaner::decrypt($params); $data = explode('|', $params); if ($data[0] != $xoopsUser->uid()) { send_error(__('Unauthorized!', 'galleries')); } if ($data[1] != GS_URL . '/admin/images.php') { send_error(__('Unauthorized!', 'galleries')); } if (!$xoopsSecurity->check(false, $data[2])) { send_error(__('Unauthorized!', 'galleries')); } $image = new GSImage($id); if ($image->isNew()) { send_error(__('Image not found!', 'galleries')); } $thSize = $mc['image_ths']; $imgSize = $mc['image']; if ($thSize[0] <= 0) { $thSize[0] = 100; } if (!isset($thSize[1]) || $thSize[1] <= 0) { $thSize[1] = $thSize[0]; } if ($imgSize[0] <= 0) { $imgSize[0] = 500; } if (!isset($imgSize[1]) || $imgSize[1] <= 0) { $imgSize[1] = $imgSize[0]; } $xu = new GSUser($image->owner(), 1); $updir = rtrim($mc['storedir'], '/') . "/" . $xu->uname(); $upurl = str_replace(XOOPS_ROOT_PATH, XOOPS_URL, $updir); $upths = rtrim($mc['storedir'], '/') . "/" . $xu->uname() . "/ths"; $width = 0; $tfile = ''; // Almacenamos la imágen original if ($mc['saveoriginal']) { copy($updir . '/' . $image->image(), $mc['storedir'] . '/originals/' . $image->image()); } $fd = pathinfo($updir . '/' . $image->image()); $filename = $image->image(); $redim = new RMImageResizer($updir . '/' . $image->image(), $updir . '/' . $image->image()); switch ($mc['redim_image']) { case 0: //Recortar miniatura $redim->resizeWidth($imgSize[0]); $redim->setTargetFile($upths . "/{$filename}"); $redim->resizeAndCrop($thSize[0], $thSize[1]); break; case 1: //Recortar imagen grande $redim->resizeWidthOrHeight($imgSize[0], $imgSize[1]); $redim->setTargetFile($upths . "/" . $image->image()); $redim->resizeWidth($thSize[0]); break; case 2: //Recortar ambas $redim->resizeWidthOrHeight($imgSize[0], $imgSize[1]); $redim->setTargetFile($upths . "/{$filename}"); $redim->resizeAndCrop($thSize[0], $thSize[1]); break; case 3: //Redimensionar $redim->resizeWidth($imgSize[0]); $redim->setTargetFile($upths . "/{$filename}"); $redim->resizeWidth($thSize[0]); break; } $tfile = $upurl . '/ths/' . $image->image(); $ret['message'] = sprintf(__('%s done!', 'galleries'), $image->image()); $ret['done'] = 1; $ret['file'] = $tfile; $ret['title'] = $image->image(); echo json_encode($ret); die; }
function apido() { if (!isset($_REQUEST['request']) || !($request = unserialize($_REQUEST['request']))) { return send_error(ARGS_ERROR, 'request can\'t empty'); } $source = $request['source']; if (strlen($source) < 1) { return send_error(ARGS_ERROR, 'source can\'t empty'); } if (!isset($GLOBALS['config']['whois'][$source]) || strlen($GLOBALS['config']['whois'][$source]) < 1) { return send_error(ARGS_ERROR, 'bad source id'); } $data = $request['data']; if (strlen($data) < 1) { return send_error(ARGS_ERROR, 'data can\'t empty'); } $ckeys = z(t($request['ckeys'])); if (strlen($ckeys) < 1) { $ckey_array = array("everything"); } else { $ckey_array = array("everything"); $keys = explode(',', $ckeys); if (is_array($keys)) { $ckey_array = array_merge($keys, $ckey_array); } } $action = v('action'); if (strlen($action) < 1) { $action = "display"; } $timeline = date("Y-m-d H:i:s"); // create channel $channel = new SaeChannel(); $mc = memcache_init(); $channel_name = 'nowboard-url-all'; if ($action == 'display') { $data = z(t($data)); } if ($url = $mc->get($channel_name)) { foreach ($ckey_array as $ckey) { $message = array('ckey' => $ckey, 'data' => $data, 'action' => $action, 'timeline' => $timeline, 'source' => $GLOBALS['config']['whois'][$source]); $channel->sendMessage($channel_name, json_encode($message)); } } /* if( is_array(c('talkman')) ) { foreach( c('talkman') as $uid ) { $channel_name = 'nowboard-url-'.$uid; if( $action == 'display' ) $data = z(t($data)); if( $url = $mc->get($channel_name) ) { foreach( $ckey_array as $ckey ) { $message = array( 'ckey' => $ckey , 'data' => $data , 'action' => $action , 'timeline' => $timeline , 'source' => $GLOBALS['config']['whois'][$source] ); $channel->sendMessage( $channel_name , json_encode($message) ); } } } } */ return send_result('send data to * # ' . $ckeys . ' from ' . $GLOBALS['config']['whois'][$source]); }
function update_comment_page($userid, $pageno) { global $USER, $DB; $resp = array('error' => ASSIGNMENT_UPLOADPDF_ERR_NONE); if (!($user = $DB->get_record('user', array('id' => $userid)))) { send_error('No such user!'); } if (!($submission = $this->get_submission($user->id))) { send_error('User has no submission to comment on!'); } $action = optional_param('action', '', PARAM_ALPHA); if ($action == 'getcomments' || $action == 'getimageurl') { if (!has_capability('mod/assignment:grade', $this->context)) { if ($userid != $USER->id || !has_capability('mod/assignment:submit', $this->context)) { // Students can view comments / images for their own assignment send_error('You do not have permission to do this'); } } } else { // All annotation requests need to have 'grade' capability if (!has_capability('mod/assignment:grade', $this->context)) { send_error('You do not have permission to do this'); } } if ($action == 'update') { $comment = new stdClass(); $comment->id = optional_param('comment_id', -1, PARAM_INT); $comment->posx = optional_param('comment_position_x', -1, PARAM_INT); $comment->posy = optional_param('comment_position_y', -1, PARAM_INT); $comment->width = optional_param('comment_width', -1, PARAM_INT); $comment->rawtext = optional_param('comment_text', null, PARAM_TEXT); $comment->colour = optional_param('comment_colour', 'yellow', PARAM_TEXT); $comment->pageno = $pageno; $comment->assignment_submission = $submission->id; if ($comment->posx < 0 || $comment->posy < 0 || $comment->width < 0 || $comment->rawtext === null) { send_error('Missing comment data'); } if ($comment->id === -1) { unset($comment->id); $oldcomments = $DB->get_records_select('assignment_uploadpdf_comment', 'assignment_submission = ? AND pageno = ? ' . 'AND posx = ? AND posy = ? AND rawtext = ?', array($comment->assignment_submission, $comment->pageno, $comment->posx, $comment->posy, $comment->rawtext)); if ($oldcomments && !empty($oldcomments)) { $comment->id = reset(array_keys($oldcomments)); } else { $comment->id = $DB->insert_record('assignment_uploadpdf_comment', $comment); } } else { $oldcomment = $DB->get_record('assignment_uploadpdf_comment', array('id' => $comment->id)); if (!$oldcomment) { unset($comment->id); $comment->id = $DB->insert_record('assignment_uploadpdf_comment', $comment); } else { if ($oldcomment->assignment_submission != $submission->id || $oldcomment->pageno != $pageno) { send_error('Comment id is for a different submission or page'); } else { $DB->update_record('assignment_uploadpdf_comment', $comment); } } } $resp['id'] = $comment->id; } elseif ($action == 'getcomments') { $comments = $DB->get_records('assignment_uploadpdf_comment', array('assignment_submission' => $submission->id, 'pageno' => $pageno)); $respcomments = array(); foreach ($comments as $comment) { $respcomment = array(); $respcomment['id'] = '' . $comment->id; $respcomment['text'] = $comment->rawtext; $respcomment['width'] = $comment->width; $respcomment['position'] = array('x' => $comment->posx, 'y' => $comment->posy); $respcomment['colour'] = $comment->colour; $respcomments[] = $respcomment; } $resp['comments'] = $respcomments; $annotations = $DB->get_records('assignment_uploadpdf_annot', array('assignment_submission' => $submission->id, 'pageno' => $pageno)); $respannotations = array(); foreach ($annotations as $annotation) { $respannotation = array(); $respannotation['id'] = '' . $annotation->id; $respannotation['type'] = $annotation->type; if ($annotation->type == 'freehand') { $respannotation['path'] = $annotation->path; if (is_null($annotation->path)) { $DB->delete_records('assignment_uploadpdf_annot', array('id' => $annotation->id)); continue; } } else { $respannotation['coords'] = array('startx' => $annotation->startx, 'starty' => $annotation->starty, 'endx' => $annotation->endx, 'endy' => $annotation->endy); } if ($annotation->type == 'stamp') { $respannotation['path'] = $annotation->path; } $respannotation['colour'] = $annotation->colour; $respannotations[] = $respannotation; } $resp['annotations'] = $respannotations; } elseif ($action == 'delete') { $commentid = optional_param('commentid', -1, PARAM_INT); if ($commentid < 0) { send_error('No comment id provided'); } $oldcomment = $DB->get_record('assignment_uploadpdf_comment', array('id' => $commentid, 'assignment_submission' => $submission->id, 'pageno' => $pageno)); if (!$oldcomment) { send_error('Could not find a comment with that id on this page'); } else { $DB->delete_records('assignment_uploadpdf_comment', array('id' => $commentid)); } } elseif ($action == 'getquicklist') { $quicklist = $DB->get_records('assignment_uploadpdf_qcklist', array('userid' => $USER->id), 'id'); $respquicklist = array(); foreach ($quicklist as $item) { $respitem = array(); $respitem['id'] = '' . $item->id; $respitem['text'] = $item->text; $respitem['width'] = $item->width; $respitem['colour'] = $item->colour; $respquicklist[] = $respitem; } $resp['quicklist'] = $respquicklist; } elseif ($action == 'addtoquicklist') { $item = new stdClass(); $item->userid = $USER->id; $item->width = optional_param('width', -1, PARAM_INT); $item->text = optional_param('text', null, PARAM_TEXT); $item->colour = optional_param('colour', 'yellow', PARAM_TEXT); if ($item->width < 0 || $item->text === null) { send_error('Missing quicklist data'); } $item->id = $DB->insert_record('assignment_uploadpdf_qcklist', $item); $resp['item'] = $item; } elseif ($action == 'removefromquicklist') { $itemid = optional_param('itemid', -1, PARAM_INT); if ($itemid < 0) { send_error('No quicklist id provided'); } $olditem = $DB->get_record('assignment_uploadpdf_qcklist', array('id' => $itemid, 'userid' => $USER->id)); if (!$olditem) { send_error('Could not find a quicklist item with that id on this page'); } else { $DB->delete_records('assignment_uploadpdf_qcklist', array('id' => $itemid)); } $resp['itemid'] = $itemid; } elseif ($action == 'getimageurl') { if ($pageno < 1) { send_error('Requested page number is too small (< 1)'); } list($imageurl, $imgwidth, $imgheight, $pagecount) = $this->get_page_image($pageno, $submission); if ($pageno > $pagecount) { send_error('Requested page number is bigger than the page count (' . $pageno . ' > ' . $pagecount . ')'); } $resp['image'] = new Object(); $resp['image']->url = $imageurl; $resp['image']->width = $imgwidth; $resp['image']->height = $imgheight; } elseif ($action == 'addannotation') { $annotation = new stdClass(); $annotation->startx = optional_param('annotation_startx', -1, PARAM_INT); $annotation->starty = optional_param('annotation_starty', -1, PARAM_INT); $annotation->endx = optional_param('annotation_endx', -1, PARAM_INT); $annotation->endy = optional_param('annotation_endy', -1, PARAM_INT); $annotation->path = optional_param('annotation_path', null, PARAM_TEXT); $annotation->colour = optional_param('annotation_colour', 'red', PARAM_TEXT); $annotation->type = optional_param('annotation_type', 'line', PARAM_TEXT); $annotation->id = optional_param('annotation_id', -1, PARAM_INT); $annotation->pageno = $pageno; $annotation->assignment_submission = $submission->id; if ($annotation->type == 'freehand') { if (!$annotation->path) { send_error('Missing annotation data'); } // Double-check path is valid list of points $points = explode(',', $annotation->path); if (count($points) % 2 != 0) { send_error('Odd number of coordinates in line - should be 2 coordinates per point'); } foreach ($points as $point) { if (!preg_match('/^\\d+$/', $point)) { send_error('Path point is invalid'); } } } else { if ($annotation->type != 'stamp') { $annotation->path = null; } if ($annotation->startx < 0 || $annotation->starty < 0 || $annotation->endx < 0 || $annotation->endy < 0) { if ($annotation->id < 0) { send_error('Missing annotation data'); } else { // OK not to send these when updating a line unset($annotation->startx); unset($annotation->starty); unset($annotation->endx); unset($annotation->endy); } } } if ($annotation->id === -1) { unset($annotation->id); $annotation->id = $DB->insert_record('assignment_uploadpdf_annot', $annotation); } else { $oldannotation = $DB->get_record('assignment_uploadpdf_annot', array('id' => $annotation->id)); if (!$oldannotation) { unset($annotation->id); $annotation->id = $DB->insert_record('assignment_uploadpdf_annot', $annotation); } else { if ($oldannotation->assignment_submission != $submission->id || $oldannotation->pageno != $pageno) { send_error('Annotation id is for a different submission or page'); } else { $DB->update_record('assignment_uploadpdf_annot', $annotation); } } } $resp['id'] = $annotation->id; } elseif ($action == 'removeannotation') { $annotationid = optional_param('annotationid', -1, PARAM_INT); if ($annotationid < 0) { send_error('No annotation id provided'); } $oldannotation = $DB->get_record('assignment_uploadpdf_annot', array('id' => $annotationid, 'assignment_submission' => $submission->id, 'pageno' => $pageno)); if (!$oldannotation) { send_error('Could not find a annotation with that id on this page'); } else { $DB->delete_records('assignment_uploadpdf_annot', array('id' => $annotationid)); } } else { send_error('Invalid action "' . $action . '"', ASSIGNMENT_UPLOADPDF_ERR_INVALID_ACTION); } echo json_encode($resp); }
/** * 系统提示 * @ApiDescription(section="Demo", description="系统提示") * @ApiLazyRoute(uri="/info",method="GET") * @ApiReturn(type="object", sample="{'code': 0,'message': 'success'}") */ public function info() { //$data['notice'] = ; return send_error('SYSTEM', '这里是信息提示页面'); }
public function external_hook($hook) { switch ($hook) { case 'event_ipn': $body = @file_get_contents('php://input'); $event_json = json_decode($body); ob_start(); echo "UCM coinbase DEBUG:<br><br>JSON: <br>\n"; print_r($event_json); echo "<br><br>\n"; $success = false; $bits = explode(':', isset($event_json->order->custom) ? $event_json->order->custom : ''); if (count($bits) == 4) { // we have our custom bits, invoice_id, invoice_payment_id and hash // check they are right $invoice_id = (int) $bits[0]; $invoice_payment_id = (int) $bits[1]; $invoice_payment_subscription_id = (int) $bits[2]; $hash = $bits[3]; $correct_hash = self::get_payment_key($invoice_id, $invoice_payment_id, $invoice_payment_subscription_id, true); if ($invoice_id && $invoice_payment_id && $hash == $correct_hash) { // This will send receipts on succesful invoices // todo - coinbase doesnt sent this callback correctly just yet if ($event_json && isset($event_json->recurring_payment) && $invoice_payment_subscription_id) { // status changes on a recurring payment. $invoice_payment_subscription = get_single('invoice_payment_subscription', 'invoice_payment_subscription_id', $invoice_payment_subscription_id); if (!$invoice_payment_subscription['date_start'] || $invoice_payment_subscription['date_start'] == '0000-00-00') { // no start date yet, set the start date now. if ($event_json->recurring_payment->status == 'active') { update_insert('invoice_payment_subscription_id', $invoice_payment_subscription_id, 'invoice_payment_subscription', array('status' => _INVOICE_SUBSCRIPTION_ACTIVE, 'date_start' => date('Y-m-d'))); } } if ($event_json->recurring_payment->status == 'paused' || $event_json->recurring_payment->status == 'canceled') { update_insert('invoice_payment_subscription_id', $invoice_payment_subscription_id, 'invoice_payment_subscription', array('status' => _INVOICE_SUBSCRIPTION_FAILED)); } } if ($event_json && isset($event_json->order->status) && $event_json->order->status == 'completed' && isset($event_json->order->total_native) && isset($event_json->order->custom)) { // crab out the custom bits so we know what to deal with. $invoice_payment_data = module_invoice::get_invoice_payment($invoice_payment_id); $currency = module_config::get_currency($invoice_payment_data['currency_id']); if ($invoice_payment_subscription_id) { // this API result is for a subscription payment. $invoice_payment_subscription = get_single('invoice_payment_subscription', 'invoice_payment_subscription_id', $invoice_payment_subscription_id); if ($invoice_payment_subscription && $invoice_payment_subscription['invoice_payment_subscription_id'] == $invoice_payment_subscription_id && $currency['code'] == $event_json->order->total_native->currency_iso) { if (!$invoice_payment_subscription['date_start'] || $invoice_payment_subscription['date_start'] == '0000-00-00') { // no start date yet, set the start date now (this should really happen in the above callback, but coinbase isn't working right now) update_insert('invoice_payment_subscription_id', $invoice_payment_subscription_id, 'invoice_payment_subscription', array('status' => _INVOICE_SUBSCRIPTION_ACTIVE, 'date_start' => date('Y-m-d'))); } // we have a subscription payment. woo! // this gets a bit tricky, we have to work out if the invoice has been generated for this subscription yet. // if this invoice hasn't been generated yet then we have to generate it. // pass this back to the invoice class so we can reuse this feature in the future. $data = module_invoice::create_new_invoice_for_subscription_payment($invoice_id, $invoice_payment_id, $invoice_payment_subscription_id); if ($data && $data['invoice_id'] && $data['invoice_payment_id']) { $next_time = time(); $next_time = strtotime('+' . abs((int) $invoice_payment_subscription['days']) . ' days', $next_time); $next_time = strtotime('+' . abs((int) $invoice_payment_subscription['months']) . ' months', $next_time); $next_time = strtotime('+' . abs((int) $invoice_payment_subscription['years']) . ' years', $next_time); update_insert('invoice_payment_subscription_id', $invoice_payment_subscription_id, 'invoice_payment_subscription', array('date_last_pay' => date('Y-m-d'), 'date_next' => date('Y-m-d', $next_time))); update_insert("invoice_payment_id", $data['invoice_payment_id'], "invoice_payment", array('date_paid' => date('Y-m-d'), 'amount' => $event_json->order->total_native->cents / 100, 'method' => self::get_payment_method_name() . ' (Subscription)', 'invoice_payment_subscription_id' => $invoice_payment_subscription_id)); self::add_payment_data($data['invoice_payment_id'], 'log', "Invoice Payment Subscription Received!"); self::add_payment_data($data['invoice_payment_id'], 'log', "API IP is " . $_SERVER['REMOTE_ADDR']); self::add_payment_data($data['invoice_payment_id'], 'log', "Received BTC: " . $event_json->order->total_btc->cents / 10000000); self::add_payment_data($data['invoice_payment_id'], 'log', "Received " . $event_json->order->total_native->currency_iso . ': ' . $event_json->order->total_native->cents / 100); self::add_payment_data($data['invoice_payment_id'], 'log', "Destination Address: " . $event_json->order->receive_address); self::add_payment_data($data['invoice_payment_id'], 'log', "Currency code matches, marking invoice as paid."); self::add_payment_data($data['invoice_payment_id'], 'log', "Raw Event Data: \n" . json_encode($event_json)); module_invoice::save_invoice($data['invoice_id'], array()); echo "Successful Subscription Payment!"; } else { send_error("Coinbase Subscription Error (failed to generate new invoice!) " . var_export($data, true)); } } else { send_error('Currency code missmatch on coinbase subscription payment'); } } else { // this is a normal once off payment. self::add_payment_data($invoice_payment_id, 'log', "API IP is " . $_SERVER['REMOTE_ADDR']); self::add_payment_data($invoice_payment_id, 'log', "Received BTC: " . $event_json->order->total_btc->cents / 10000000); self::add_payment_data($invoice_payment_id, 'log', "Received " . $event_json->order->total_native->currency_iso . ': ' . $event_json->order->total_native->cents / 100); self::add_payment_data($invoice_payment_id, 'log', "Destination Address: " . $event_json->order->receive_address); if ($currency['code'] == $event_json->order->total_native->currency_iso) { self::add_payment_data($invoice_payment_id, 'log', "Currency code matches, marking invoice as paid."); update_insert("invoice_payment_id", $invoice_payment_id, "invoice_payment", array('date_paid' => date('Y-m-d'), 'amount' => $event_json->order->total_native->cents / 100)); module_invoice::save_invoice($invoice_id, array()); echo "Successful Payment!"; $success = true; } else { self::add_payment_data($invoice_payment_id, 'log', "Currency code missmatch, please check settings!"); } self::add_payment_data($invoice_payment_id, 'log', "Raw Event Data: \n" . json_encode($event_json)); } } } } $debug = ob_get_clean(); if (module_config::c('coinbase_payment_debug', 0)) { send_error("Coinbase Debug: {$debug}"); } exit; break; case 'pay_subscription': $invoice_id = isset($_REQUEST['invoice_id']) ? $_REQUEST['invoice_id'] : false; $invoice_payment_id = isset($_REQUEST['invoice_payment_id']) ? $_REQUEST['invoice_payment_id'] : false; $invoice_payment_subscription_id = isset($_REQUEST['invoice_payment_subscription_id']) ? $_REQUEST['invoice_payment_subscription_id'] : false; $coinbase_plan_id = isset($_REQUEST['coinbase_plan_id']) ? $_REQUEST['coinbase_plan_id'] : false; $user_id = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : false; if ($invoice_id && $invoice_payment_id && $coinbase_plan_id && $invoice_payment_subscription_id && $user_id && isset($_POST['coinbaseToken'])) { $user_data = module_user::get_user($user_id); $email = isset($_REQUEST['coinbaseEmail']) && strlen($_REQUEST['coinbaseEmail']) ? $_REQUEST['coinbaseEmail'] : $user_data['email']; if (!$email || !strpos($email, '@')) { die('Please ensure your user account has a valid email address before paying with coinbase'); } $invoice_payment = get_single('invoice_payment', 'invoice_payment_id', $invoice_payment_id); $invoice_payment_subscription = get_single('invoice_payment_subscription', 'invoice_payment_subscription_id', $invoice_payment_subscription_id); if (!$invoice_payment || !$invoice_payment_subscription || $invoice_payment['invoice_id'] != $invoice_id || $invoice_payment['invoice_payment_subscription_id'] != $invoice_payment_subscription_id) { die('Invalid invoice payment subscription id'); } $invoice_payment_data = module_invoice::get_invoice_payment($invoice_payment_id); $invoice_data = module_invoice::get_invoice($invoice_id); if ($invoice_payment_data && $invoice_data && $invoice_id == $invoice_data['invoice_id'] && $invoice_payment_data['invoice_id'] == $invoice_data['invoice_id']) { $currency = module_config::get_currency($invoice_payment_data['currency_id']); $currency_code = $currency['code']; $description = isset($_REQUEST['description']) ? $_REQUEST['description'] : 'N/A'; $template = new module_template(); ob_start(); require_once 'includes/plugin_paymethod_coinbase/coinbase-php/lib/coinbase.php'; $coinbase = array("secret_key" => module_config::c('payment_method_coinbase_api_key'), "publishable_key" => module_config::c('payment_method_coinbase_secret_key')); coinbase::setApiKey($coinbase['secret_key']); try { // todo- search for existing customer based on email address??? // todo: check if adding new plan to existing customer work?? $coinbase_customer = coinbase_Customer::create(array("card" => $_POST['coinbaseToken'], "email" => $email, 'metadata' => array('user_id' => $user_id))); if ($coinbase_customer && $coinbase_customer->id) { //} && $coinbase_customer->subscriptions){ $coinbase_subscription = $coinbase_customer->subscriptions->create(array('plan' => $coinbase_plan_id)); if ($coinbase_subscription && $coinbase_subscription->id) { update_insert('invoice_payment_subscription_id', $invoice_payment_subscription_id, 'invoice_payment_subscription', array('status' => _INVOICE_SUBSCRIPTION_ACTIVE, 'date_start' => date('Y-m-d'), 'coinbase_customer' => $coinbase_customer->id, 'coinbase_subscription' => $coinbase_subscription->id)); module_paymethod_coinbase::add_payment_data($invoice_payment_id, 'log', "Started coinbase Subscription: " . var_export(array('customer.id' => $coinbase_customer->id, 'plan.id' => $coinbase_plan_id, 'subscription.id' => $coinbase_subscription->id), true)); // success! // redirect to receipt page. redirect_browser(module_invoice::link_public_payment_complete($invoice_id)); } else { echo 'Failed to create subscription with coinbase'; } } $error = "Something went wrong during coinbase payment. Please confirm invoice payment went through: " . htmlspecialchars($description); send_error($error); echo $error; } catch (coinbase_CardError $e) { // The card has been declined $body = $e->getJsonBody(); $err = $body['error']; $error = "Sorry: Payment failed. <br><br>\n\n" . htmlspecialchars($description) . ". <br><br>\n\n"; $error .= $err['message']; echo $error; $error .= "\n\n\n" . var_export($err, true); send_error($error); } catch (Exception $e) { $body = $e->getJsonBody(); $err = $body['error']; $error = "Sorry: Payment failed. <br><br>\n\n" . htmlspecialchars($description) . ". <br><br>\n\n"; $error .= $err['message']; echo $error; $error .= "\n\n\n" . var_export($err, true); send_error($error); } $template->content = ob_get_clean(); echo $template->render('pretty_html'); exit; } } echo 'Error paying via coinbase'; exit; } }
$pageno = required_param('pageno', PARAM_INT); if ($id) { if (!($cm = get_coursemodule_from_id('assignment', $id))) { send_error("Course Module ID was incorrect"); } if (!($assignment = get_record("assignment", "id", $cm->instance))) { send_error("assignment ID was incorrect"); } if (!($course = get_record("course", "id", $assignment->course))) { send_error("Course is misconfigured"); } } else { if (!($assignment = get_record("assignment", "id", $a))) { send_error("Course module is incorrect"); } if (!($course = get_record("course", "id", $assignment->course))) { send_error("Course is misconfigured"); } if (!($cm = get_coursemodule_from_instance("assignment", $assignment->id, $course->id))) { send_error("Course Module ID was incorrect"); } } require_login($course->id, false, $cm); // Students are allowed to view comments on their own assignments, so capabilities now checked later //require_capability('mod/assignment:grade', get_context_instance(CONTEXT_MODULE, $cm->id)); if (!confirm_sesskey()) { send_error('You must be logged in to do this', ASSIGNMENT_UPLOADPDF_ERR_NO_LOGIN); } require_once dirname(__FILE__) . '/assignment.class.php'; $assignmentinstance = new assignment_uploadpdf($cm->id, $assignment, $cm, $course); $assignmentinstance->update_comment_page($userid, $pageno);
public function external_hook($hook) { switch ($hook) { case 'notification': if (!isset($_REQUEST['serial-number']) || !$_REQUEST['serial-number']) { send_error('Google API not setup correctly. Please ensure API callback URL is set correctly as per instructions'); exit; } chdir(dirname(__FILE__)); //'includes/plugin_paymethod_google/'); require_once 'library/googleresponse.php'; //require_once('library/googlemerchantcalculations.php'); require_once 'library/googleresult.php'; require_once 'library/googlerequest.php'; require_once 'library/googlenotification.php'; require_once 'library/googlenotificationhistory.php'; define('RESPONSE_HANDLER_ERROR_LOG_FILE', _UCM_FOLDER . '/temp/googleerror.log'); define('RESPONSE_HANDLER_LOG_FILE', _UCM_FOLDER . '/temp/googlemessage.log'); $server_type = self::is_sandbox() ? "sandbox" : ''; //$currency = module_config::get_currency($currency_id); //$Gresponse = new GoogleResponse(self::get_merchant_id(), self::get_merchant_key()); $Grequest = new GoogleRequest(self::get_merchant_id(), self::get_merchant_key(), $server_type); $GNotificationHistory = new GoogleNotificationHistoryRequest(self::get_merchant_id(), self::get_merchant_key(), $server_type); $response = $GNotificationHistory->SendNotificationHistoryRequest($_REQUEST['serial-number']); $xml_response_status = $response[0]; $xml_response = $response[1]; $response = new SimpleXMLElement($xml_response); $root = $response->getName(); // debugging //send_error('xml2: '.$root.var_export($response,true)); //$Gresponse->SetMerchantAuthentication(self::get_merchant_id(), self::get_merchant_key()); //$Gresponse->SendAck(); $google_order_number = (string) $response->{'google-order-number'}; if ($google_order_number) { $invoice_payment_data = get_single('invoice_payment', 'other_id', $google_order_number); } else { $invoice_payment_data = false; send_error('Google payment API failure, no Google Order Number located'); } if ($invoice_payment_data && $invoice_payment_data['invoice_payment_id']) { self::add_payment_data($invoice_payment_data['invoice_payment_id'], 'log', 'Recorded an API hit: ' . $root); } switch ($root) { case "new-order-notification": // an order has been placed. // dont really need to do anything. // we grab the merchant private data from this bit // it contains the private id etc.. if ($google_order_number && $response->{'shopping-cart'}->{'merchant-private-data'}) { $private_data = (array) $response->{'shopping-cart'}->{'merchant-private-data'}; $invoice_id = (int) $private_data['invoice_id']; $invoice_payment_id = (int) $private_data['invoice_payment_id']; if ($invoice_id > 0 && $invoice_payment_id > 0) { self::add_payment_data($invoice_payment_id, 'log', 'Found Google Order Number: ' . $google_order_number); $sql = "UPDATE `" . _DB_PREFIX . "invoice_payment` SET `other_id` = '" . mysql_real_escape_string($google_order_number) . "' WHERE invoice_id = '{$invoice_id}' AND invoice_payment_id = '{$invoice_payment_id}'"; query($sql); } } break; case "order-state-change-notification": $new_financial_state = (string) $response->{'new-financial-order-state'}; if ($invoice_payment_data && $invoice_payment_data['invoice_payment_id']) { self::add_payment_data($invoice_payment_data['invoice_payment_id'], 'log', 'Recorded an order status change to: ' . $new_financial_state); } switch ($new_financial_state) { case 'REVIEWING': break; case 'CHARGEABLE': if ($invoice_payment_data && $invoice_payment_data['invoice_payment_id']) { self::add_payment_data($invoice_payment_data['invoice_payment_id'], 'log', 'Charging customers credit card. '); } // process and charge the order: $Grequest->SendProcessOrder($google_order_number); $Grequest->SendChargeOrder($google_order_number, ''); break; case 'CHARGING': break; case 'CHARGED': break; case 'PAYMENT_DECLINED': break; case 'CANCELLED': break; case 'CANCELLED_BY_GOOGLE': //$Grequest->SendBuyerMessage($data[$root]['google-order-number']['VALUE'], // "Sorry, your order is cancelled by Google", true); break; default: break; } break; case "charge-amount-notification": // payment has been made! // update the order. $Grequest->SendArchiveOrder($google_order_number); if ($invoice_payment_data && $invoice_payment_data['invoice_payment_id']) { self::add_payment_data($invoice_payment_data['invoice_payment_id'], 'log', 'Received a payment of ' . $response->{'latest-charge-amount'} . ' and assigning it to this invoice.'); update_insert("invoice_payment_id", $invoice_payment_data['invoice_payment_id'], "invoice_payment", array('date_paid' => date('Y-m-d'))); } break; case "chargeback-amount-notification": break; case "refund-amount-notification": break; case "risk-information-notification": break; default: //$Gresponse->SendBadRequestStatus("Invalid or not supported Message"); break; } break; } }
$user_controller = new User_Controller($user); $Logged_In = $user_controller->login(); if ($Logged_In) { //get the new user //and from the new user find the type of the user $Logged_In_User = $user_controller->getUser(); $user_type = $Logged_In_User->getUserType(); if ($user_type == User_Type::OPERATOR) { redirect_user(User_Type::OPERATOR); } else { if ($user_type == User_Type::ENCODER) { redirect_user(User_Type::ENCODER); } else { if ($user_type == User_Type::NORMAL_ENCODER) { redirect_user(User_Type::NORMAL_ENCODER); } else { if ($user_type == User_Type::ADMIN) { redirect_user(User_Type::ADMIN); } } } } } else { //this function will send errors that the credential the users has entered is not correct send_error("credential_error"); } } else { //send error to the login page that the forms are not filled send_error("fill_error"); } }
$data = json_decode($_POST['data'], true); if ($data !== null && $data !== false) { $result = Utils::remove_from_future_list($data); if (count($result) == 0) { send_error('item is not in file'); } else { if (count($result) > 0) { $result = array('status' => 'ok') + $result; echo json_encode($result); } } } else { send_error('cannot parse json data'); } } else { send_error('data param does not set'); } break; } } function send_error($error_text) { $arr['error'] = $error_text; echo json_encode($arr); } function update_and_supress_output($data) { $cr = new ConfigReader(); $cr->udate_pending_items_count(-count($data)); return true; }
public function run_cron($debug = false) { // check for payments. $sql = "SELECT * FROM `" . _DB_PREFIX . "invoice_payment` ip WHERE 1 "; $sql .= " AND `method` = 'paynl' "; $sql .= " AND `date_paid` = '0000-00-00' "; $sql .= " AND `other_id` != '' "; foreach (qa($sql) as $payment) { // check api status: $strUrl = 'https://*****:*****@rest-api.pay.nl/v5/Transaction/info/json?'; $arrArguments = array(); $arrArguments['transactionId'] = $payment['other_id']; # Prepare and call API URL $strUrl .= http_build_query($arrArguments); if ($debug) { echo "Checking URL {$strUrl} <br>\n"; $jsonResult = file_get_contents($strUrl); } else { $jsonResult = @file_get_contents($strUrl); } $json = @json_decode($jsonResult, true); if ($debug) { echo "Got result: <br>\n"; print_r($json); } if ($json && isset($json['paymentDetails']) && isset($json['paymentDetails']['stateName']) && isset($json['paymentDetails']['amount'])) { module_paymethod_paynl::add_payment_data($payment['invoice_payment_id'], 'log', "PayNL Status " . $json['paymentDetails']['stateName'] . ": \n " . var_export($json, true)); switch ($json['paymentDetails']['stateName']) { case 'PENDING': // defauly, still waiting for payment. break; case 'PAID': update_insert("invoice_payment_id", $payment['invoice_payment_id'], "invoice_payment", array('date_paid' => date('Y-m-d'), 'amount' => $json['paymentDetails']['amount'] / 100, 'other_id' => '')); module_invoice::save_invoice($payment['invoice_id'], array()); break; case 'CANCEL': update_insert("invoice_payment_id", $payment['invoice_payment_id'], "invoice_payment", array('other_id' => '')); module_invoice::save_invoice($payment['invoice_id'], array()); send_error('PayNL payment cancelled for invoice: ' . module_invoice::link_open($payment['invoice_id'], true)); break; } } else { module_paymethod_paynl::add_payment_data($payment['invoice_payment_id'], 'log', "PayNL Status ERROR: \n " . $jsonResult); } } }
// Only keep the ones that pass foreach ($ranges as $range) { $offset = parse_offset($range, $filelength); if ($offset !== false) { $offsets[] = $offset; } } /* Depending on the number of valid ranges requested, you must return different the response in a different format */ switch (count($offsets)) { case 0: // No valid ranges error_log("Client requested no valid ranges."); send_error($filelength); exit; break; case 1: // One valid range, send standard reply http_response_code(206); // Partial Content list($start, $end) = $offsets[0]; header("Content-Range: bytes {$start}-{$end}/{$filelength}"); header("Content-Type: {$content_type}"); // Set variables to allow code reuse code across this case and the next one // Note: 0-0 is 1 byte long, because we're inclusive $content_length = $end - $start + 1; $boundaries = array(0 => '', 1 => ''); break; default:
foreach ($_POST["modid"] as $id) { $addmodulesql = "select addmodule({$testid}, \"" . $_POST["modname"][$id] . "\", \"" . $_POST["moddesc"][$id] . "\", " . $_POST["moddura"][$id] . "," . $_POST['modtypeisany'][$id] . "," . $_POST['modqua'][$id] . ")"; $res = mysql_query($addmodulesql); $er = mysql_error(); if ($er != "") { send_error($er); } $row = mysql_fetch_array($res); mysql_free_result($res); $modid = $row[0]; foreach ($_POST["modid-" . $id . "-subqsn"] as $key => $qsn) { $sql = "insert into es_mod_sub (ms_mod_id,ms_sub_id,ms_no_qsn)values({$modid},\"" . $_POST["modid-" . $id . "-subid"][$key] . "\",\"" . $qsn . "\")"; mysql_query($sql); $er = mysql_error(); if ($er != "") { send_error($er); } } } /*header("Content-Type: application/xml; charset=utf-8"); echo '<?xml version="1.0" encoding="utf-8"?>'; endpage();*/ sendjsondata(); } if (isset($_GET['token']) && $_GET['token'] == 'setup') { //sleep(1); $sql = "select * from es_sub"; $res = mysql_query($sql); $str = ""; while ($row = mysql_fetch_array($res)) { /*$str .= "\t<sub>\n";
function send_response($username, $authorize = false) { $GET = $_SESSION['get']; $rpfA = $_SESSION['rpfA']; $rpep = $GET['redirect_uri']; $state = isset($GET['state']) ? $GET['state'] : NULL; $error_page = isset($GET['redirect_uri']) ? $GET['redirect_uri'] : OP_INDEX_PAGE; $response_mode = get_response_mode($GET); try { $client_id = $GET['client_id']; $response_types = explode(' ', $GET['response_type']); $scopes = explode(' ', $GET['scope']); $prompts = explode(' ', $GET['prompt']); $is_code_flow = in_array('code', $response_types); $is_token_flow = in_array('token', $response_types); $is_id_token = in_array('id_token', $response_types); $offline_access = $is_code_flow && !$is_token_flow && in_array('consent', $prompts) && in_array('offline_access', $scopes); $issue_at = strftime('%G-%m-%d %T'); $expiration_at = strftime('%G-%m-%d %T', time() + 2 * 60); $response_params = array(); if (!$authorize) { throw new OidcException('access_denied', 'User denied access'); } $rpfA['session_id'] = session_id(); $rpfA['auth_time'] = $_SESSION['auth_time']; $confirmed_attribute_list = get_all_requested_claims($rpfA, $GET['scope']); if ($is_code_flow) { $code_info = create_token_info($username, $confirmed_attribute_list, $GET, $rpfA); $code = $code_info['name']; unset($code_info['name']); $fields = array('client' => $GET['client_id'], 'issued_at' => $issue_at, 'expiration_at' => $expiration_at, 'token' => $code, 'details' => '', 'token_type' => TOKEN_TYPE_AUTH_CODE, 'info' => json_encode($code_info)); db_save_user_token($username, $code, $fields); } if ($is_token_flow) { $code_info = create_token_info($username, $confirmed_attribute_list, $GET, $rpfA); $token = $code_info['name']; unset($code_info['name']); $issue_at = strftime('%G-%m-%d %T'); $expiration_at = strftime('%G-%m-%d %T', time() + 2 * 60); $fields = array('client' => $GET['client_id'], 'issued_at' => $issue_at, 'expiration_at' => $expiration_at, 'token' => $token, 'details' => '', 'token_type' => TOKEN_TYPE_ACCESS, 'info' => json_encode($code_info)); db_save_user_token($username, $token, $fields); } if ($offline_access) { while (true) { $refresh_token_name = base64url_encode(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM)); if (!db_find_token($refresh_token_name)) { break; } } $fields = array('client' => $GET['client_id'], 'issued_at' => $issue_at, 'expiration_at' => $expiration_at, 'token' => $refresh_token_name, 'details' => '', 'token_type' => TOKEN_TYPE_REFRESH, 'info' => json_encode($code_info)); $fields['expiration_at'] = strftime('%G-%m-%d %T', time() + 24 * 60 * 60); db_save_user_token($username, $refresh_token_name, $fields); } // Handle response_type for code or token if (isset($GET['state'])) { $response_params['state'] = $GET['state']; } if ($is_token_flow || $is_id_token) { if (isset($token)) { $response_params['access_token'] = $token; $response_params['token_type'] = 'Bearer'; if ($offline_access) { $response_params['refresh_token'] = $refresh_token_name; } $response_params['expires_in'] = '3600'; } } if ($is_id_token) { $client_secret = null; $nonce = isset($GET['nonce']) ? $GET['nonce'] : null; $c_hash = null; $at_hash = null; $ops = null; $auth_time = null; $acr = null; $idt_claims = array(); $sig = null; $alg = null; $enc = null; $client_secret = null; $jwk_uri = null; $db_client = db_get_client($client_id); if ($db_client) { $sig = $db_client['id_token_signed_response_alg']; if (!isset($sig)) { $sig = 'RS256'; } $alg = $db_client['id_token_encrypted_response_alg']; $enc = $db_client['id_token_encrypted_response_enc']; $client_secret = $db_client['client_secret']; $jwk_uri = $db_client['jwks_uri']; $jwks = $db_client['jwks']; } if (isset($rpfA['claims']) && isset($rpfA['claims']['id_token'])) { if (array_key_exists('auth_time', $rpfA['claims']['id_token'])) { $auth_time = (int) $_SESSION['auth_time']; } if (array_key_exists('acr', $rpfA['claims']['id_token'])) { if (array_key_exists('values', $rpfA['claims']['id_token']['acr'])) { if (is_array($rpfA['claims']['id_token']['acr']['values']) && count($rpfA['claims']['id_token']['acr']['values'])) { $acr = $rpfA['claims']['id_token']['acr']['values'][0]; } } else { $acr = '0'; } } } if ($sig) { $bit_length = substr($sig, 2); switch ($bit_length) { case '384': $hash_alg = 'sha384'; break; case '512': $hash_alg = 'sha512'; break; case '256': default: $hash_alg = 'sha256'; break; } $hash_length = (int) ((int) $bit_length / 2) / 8; if ($code) { $c_hash = base64url_encode(substr(hash($hash_alg, $code, true), 0, $hash_length)); } if ($token) { $at_hash = base64url_encode(substr(hash($hash_alg, $token, true), 0, $hash_length)); } } $requested_id_token_claims = get_id_token_claims($rpfA); if ($requested_id_token_claims) { $db_user = db_get_user($username); if ($db_user) { $idt_claims = get_account_claims($db_user, $requested_id_token_claims); } else { throw new OidcException('access_denied', 'no such user'); } } $id_token_obj = make_id_token(wrap_userid($db_client, $username), SERVER_ID, $client_id, $idt_claims, $nonce, $c_hash, $at_hash, $auth_time, $ops, $acr); log_debug('sen_response id_token_obj = %s', print_r($id_token_obj, true)); $cryptoError = null; $id_token = sign_encrypt($id_token_obj, $sig, $alg, $enc, $jwk_uri, $jwks, $client_secret, $cryptoError); if (!$id_token) { log_error("Unable to sign encrypt response for ID Token %s", $cryptoError); throw new OidcException('invalid_request', "idtoken crypto error {$cryptoError}"); } $response_params['id_token'] = $id_token; } $url_parts = parse_url($rpep); $origin = sprintf("%s://%s%s", $url_parts['scheme'], $url_parts['host'], isset($url_parts['port']) ? ':' . $url_parts['port'] : ''); $salt = bin2hex(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)); log_debug("ss = sha256(%s%s%s%s).%s", $client_id, $origin, $_SESSION['ops'], $salt, $salt); $session_state = hash('sha256', "{$client_id}{$origin}{$_SESSION['ops']}{$salt}") . '.' . $salt; $response_params['session_state'] = $session_state; if ($is_code_flow) { $response_params['code'] = $code; } if ($_SESSION['persist'] == 'on') { $username = $_SESSION['username']; $auth_time = $_SESSION['auth_time']; $ops = $_SESSION['ops']; $login = $_SESSION['login']; clean_session(); $_SESSION['lastlogin'] = time(); $_SESSION['username'] = $username; $_SESSION['auth_time'] = $auth_time; $_SESSION['ops'] = $ops; $_SESSION['login'] = $login; $_SESSION['persist'] = 'on'; } else { session_destroy(); } send_auth_response($rpep, $response_params, $response_mode); } catch (OidcException $e) { log_error("handle_auth exception : %s", $e->getTraceAsString()); send_error($error_page, $e->error_code, $e->desc, NULL, $state, $response_mode); } catch (Exception $e) { log_error("handle_auth exception : %s", $e->getTraceAsString()); send_error($error_page, 'invalid_request', $e->getMessage(), NULL, $state, $response_mode); } }
function render($data, $layout = null, $sharp = 'default') { if ($layout == null) { if (is_ajax_request()) { $layout = 'ajax'; } else { $layout = 'web'; } } $GLOBALS['layout'] = $layout; $GLOBALS['sharp'] = $sharp; $layout_file = AROOT . 'view' . DS . $layout . DS . $sharp . '.tpl.php'; if (file_exists($layout_file)) { @extract($data); return require $layout_file; } else { // 模板文件不存在 return send_error('TMPLATE', 'file ' . $layout_file . ' not exists ', true); } }