Example #1
1
function ea_email_sent_shortcode()
{
    ob_start();
    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // Reading from superglobals
    $tCallerSkypeNameSg = esc_sql($_POST["skype_name"]);
    // ..verifying that the skype name exists
    if (verifyUserNameExists($tCallerSkypeNameSg) === false) {
        echo "<h3><i><b>Incorrect Skype name</b> - email not sent. Please go back and try again.</i></h3>";
        exit;
    }
    $tLengthNr = $_POST["length"];
    if (is_numeric($tLengthNr) === false) {
        handleError("Length variable was not numeric - possible SQL injection attempt");
    }
    // Setting up variables based on the superglobals
    $tCallerIdNr = getIdByUserName($tCallerSkypeNameSg);
    $tUniqueDbIdentifierSg = uniqid("id-", true);
    // http://php.net/manual/en/function.uniqid.php
    $tCallerDisplayNameSg = getDisplayNameById($tCallerIdNr);
    $tCallerEmailSg = getEmailById($tCallerIdNr);
    $tEmpathizerDisplayNameSg = getDisplayNameById(get_current_user_id());
    // If this is the first call: reduce the donation amount.
    $tAdjustedLengthNr = $tLengthNr;
    if (isFirstCall($tCallerIdNr) == true) {
        $tAdjustedLengthNr = $tAdjustedLengthNr - Constants::initial_call_minute_reduction;
    }
    $tRecDonationNr = (int) round(get_donation_multiplier() * $tAdjustedLengthNr);
    // Create the contents of the email message.
    $tMessageSg = "Hi " . $tCallerDisplayNameSg . ",\n\nThank you so much for your recent empathy call! Congratulations on contributing to a more empathic world. :)\n\nYou talked with: {$tEmpathizerDisplayNameSg}\nYour Skype session duration was: {$tLengthNr} minutes\nYour recommended contribution is: \${$tRecDonationNr}\n\nPlease follow this link to complete payment within 24 hours: " . getBaseUrl() . pages::donation_form . "?recamount={$tRecDonationNr}&dbToken={$tUniqueDbIdentifierSg}\n\nSee you next time!\n\nThe Empathy Team\n\nPS\nIf you have any feedback please feel free to reply to this email and tell us your ideas or just your experience!\n";
    // If the donation is greater than 0: send an email to the caller.
    if ($tRecDonationNr > 0) {
        ea_send_email($tCallerEmailSg, "Empathy App Payment", $tMessageSg);
        echo "<h3>Email successfully sent to caller.</h3>";
    } else {
        echo "<h4>No email sent: first time caller and call length was five minutes or less.</h4>";
    }
    // Add a new row to the db CallRecords table.
    db_insert(array(DatabaseAttributes::date_and_time => current_time('mysql', 1), DatabaseAttributes::recommended_donation => $tRecDonationNr, DatabaseAttributes::call_length => $tLengthNr, DatabaseAttributes::database_token => $tUniqueDbIdentifierSg, DatabaseAttributes::caller_id => $tCallerIdNr, DatabaseAttributes::empathizer_id => get_current_user_id()));
    $ob_content = ob_get_contents();
    //+++++++++++++++++++++++++++++++++++++++++
    ob_end_clean();
    return $ob_content;
}
/**
 * Exportiert eine MySQL Tabelle ins Excel format und sendet die Datei zum Browser
 * @param string $location Speicherort auf dem Server
 * @param string $filename Dateiname mit dem die Datei zum Download angeboten wird
 * @param mysql_result $mysql_result Resultobject von mysql_query
 */
function rs2xls($location, $filename, $mysql_result)
{
    $filename = str_replace(' ', '_', $filename);
    $filename = str_replace('ä', 'ae', $filename);
    $filename = str_replace('ö', 'oe', $filename);
    $filename = str_replace('ü', 'ue', $filename);
    $filename = str_replace('Ä', 'Ae', $filename);
    $filename = str_replace('Ö', 'Oe', $filename);
    $filename = str_replace('Ü', 'Ue', $filename);
    $xls =& new Spreadsheet_Excel_Writer($location);
    // Send HTTP headers to tell the browser what's coming
    // handleError( $xls->send( $filename));
    // Arbeitsblatt hinzufügen
    handleError($sheet =& $xls->addWorksheet('Tabelle1'));
    $printHeaders = true;
    $line = 0;
    while (($row = mysql_fetch_row($mysql_result)) !== false) {
        if ($printHeaders) {
            for ($i = 0; $i < count($row); $i++) {
                $column = ucwords(mysql_field_name($mysql_result, $i));
                handleError($sheet->write($line, $i, $column));
            }
            $line++;
            $printHeaders = false;
        }
        for ($i = 0; $i < count($row); $i++) {
            handleError($sheet->write($line, $i, $row[$i]));
        }
        $line++;
    }
    handleError($xls->close());
    return $filename;
}
Example #3
0
 function hasObjectRights(&$hasRight, $method, $giveError = FALSE)
 {
     hasAdminRights($isAdm);
     $hasRight->objectRight = $isAdm;
     if (!$hasRight && $giveError) {
         handleError($lll["permission_denied"]);
     }
 }
Example #4
0
 function hasObjectRights(&$hasRight, $method, $giveError = FALSE)
 {
     global $lll;
     hasAdminRights($isAdm);
     $hasRight->objectRight = ($method == "modify" || $method == "load") && $isAdm;
     if (!$hasRight->objectRight && $giveError) {
         handleError($lll["permission_denied"]);
     }
 }
Example #5
0
 /**
  * execute
  *
  * @return void
  */
 public function execute()
 {
     if ($this->validate()) {
         try {
             $this->{$this->_params['action']}();
         } catch (Exception $e) {
             handleError($e->getMessage(), $e->getCode());
         }
     }
 }
Example #6
0
 function hasObjectRights(&$hasRight, $method, $giveError = FALSE)
 {
     global $lll;
     hasAdminRights($isAdm);
     $hasRight->objectRight = $isAdm && $method == "modify" || $method == "load";
     $hasRight->generalRight = TRUE;
     if (!$hasRight->objectRight && $giveError) {
         handleError($lll["permission_denied"]);
     }
     return ok;
 }
Example #7
0
 function hasObjectRights(&$hasRight, $method, $giveError = FALSE)
 {
     global $lll;
     parent::hasObjectRights($hasRight, $method, $giveError);
     if ($method == "modify") {
         $hasRight->generalRight = FALSE;
     }
     if ($hasRight->objectRight == TRUE && $method == "modify" && $this->disableModify()) {
         $hasRight->objectRight = FALSE;
     }
     if (!$hasRight->objectRight && $giveError) {
         handleError($lll["permission_denied"]);
     }
 }
Example #8
0
 function hasObjectRights(&$hasRight, $method, $giveError = FALSE)
 {
     global $lll;
     hasAdminRights($isAdm);
     $hasRight->generalRight = TRUE;
     if ($method == "delete") {
         $hasRight->generalRight = FALSE;
         $hasRight->objectRight = $isAdm && $this->isFixField() === FALSE;
     } else {
         $hasRight->objectRight = $method == "load" || $isAdm;
     }
     if (!$hasRight->objectRight && $giveError) {
         handleError($lll["permission_denied"]);
     }
 }
function serveFileFromZIP($baseDir, $zipName, $fileName)
{
    $zip = new ZipArchive();
    if ($zip->open($baseDir . $zipName) !== TRUE) {
        handleError("Could not open ZIP file '{$zipName}'");
    }
    $contents = $zip->getStream($fileName);
    if ($contents === FALSE) {
        $zip->close();
        handleError("Could not find file '{$fileName}' in ZIP file '{$zipName}'");
    }
    $fileSize = $zip->statName($fileName)['size'];
    header('Content-Length: ' . $fileSize);
    header('Content-Type: text/plain');
    fpassthru($contents);
    fclose($contents);
    $zip->close();
    exit;
}
Example #10
0
 function prepare_items()
 {
     //
     global $wpdb;
     $tTableNameSg = getCallRecordTableName();
     $tQuerySg = "SELECT * FROM {$tTableNameSg}";
     // Setup of ordering.
     // (At present we don't use the GET params for this, but maybe in the future)
     $tOrderBySg = !empty($_GET["orderby"]) ? esc_sql($_GET["orderby"]) : 'DESC';
     $tOrderSg = !empty($_GET["order"]) ? esc_sql($_GET["order"]) : DatabaseAttributes::id;
     if (!empty($tOrderBySg) && !empty($tOrderSg)) {
         $tQuerySg .= ' ORDER BY ' . $tOrderSg . ' ' . $tOrderBySg;
     }
     $tTotalNrOfItemsNr = $wpdb->query($tQuerySg);
     $tNumberOfItemsPerPageNr = Constants::record_rows_display_max;
     $tPagedSg = '';
     if (isset($_GET["paged"])) {
         $tPagedSg = $_GET["paged"];
     }
     if (empty($tPagedSg) === false) {
         if (is_numeric($tPagedSg) === false) {
             handleError("Page number contained non-numeric characters, possible SQL injection attempt");
         }
     }
     // Limiting the range of results returned.
     // (We don't want to display all the rows one a single page)
     // Documenation for MySQL "LIMIT":
     // http://www.w3schools.com/php/php_mysql_select_limit.asp
     if (empty($tPagedSg) || !is_numeric($tPagedSg) || $tPagedSg <= 0) {
         $tPagedSg = 1;
     }
     $tTotalNrOfPagesNr = ceil($tTotalNrOfItemsNr / $tNumberOfItemsPerPageNr);
     if (!empty($tPagedSg) && !empty($tNumberOfItemsPerPageNr)) {
         $tNumberOfItemsOffsetNr = ($tPagedSg - 1) * $tNumberOfItemsPerPageNr;
         $tQuerySg .= ' LIMIT ' . (int) $tNumberOfItemsPerPageNr . ' OFFSET ' . (int) $tNumberOfItemsOffsetNr;
     }
     $this->set_pagination_args(array("total_items" => $tTotalNrOfItemsNr, "total_pages" => $tTotalNrOfPagesNr, "per_page" => $tNumberOfItemsPerPageNr));
     // Updating the data available for this class; this data will later be
     // rendered for the user
     $tColumnsAr = $this->get_columns();
     $this->_column_headers = array($tColumnsAr, array(), array());
     $this->items = $wpdb->get_results($tQuerySg);
 }
function getRankedStats()
{
    global $apiKey, $playerID, $playerServer;
    $url = 'https://' . $playerServer . '.api.pvp.net/api/lol/' . $playerServer . '/v1.3/stats/by-summoner/' . $playerID . '/ranked?season=SEASON2015&api_key=' . $apiKey;
    $response = file_get_contents($url);
    if (requestFailed($response, $url)) {
        $error = error_get_last();
        $error = $error['message'];
        $errorCode = substr($error, strpos($error, "/1.1") + 5, 3);
        handleError($errorCode, $url, "champions on ranked");
        return;
    }
    $rankedStats = json_decode($response);
    $championsPlayed = $rankedStats->champions;
    $url = 'https://global.api.pvp.net/api/lol/static-data/' . $playerServer . '/v1.2/champion?champData=image&api_key=' . $apiKey;
    $response = file_get_contents($url);
    if (requestFailed($response, $url)) {
        $error = error_get_last();
        $error = $error['message'];
        $errorCode = substr($error, strpos($error, "/1.1") + 5, 3);
        handleError($errorCode, $url, "champions");
        return;
    }
    $champions = json_decode($response)->data;
    $playerChampions = array();
    foreach ($champions as $key => $champion) {
        foreach ($championsPlayed as $key => $championPlayed) {
            if ($championPlayed->id == $champion->id) {
                $champ = new Champion();
                $champ->name = $champion->name;
                $champ->id = $champion->id;
                $champ->title = $champion->title;
                $champ->image = $champion->image->full;
                $champ->stats = $championPlayed->stats;
                array_push($playerChampions, $champ);
                break;
            }
        }
    }
    usort($playerChampions, "sortChamps");
    echo json_encode($playerChampions);
}
Example #12
0
 /**
  * @return put return description here..
  * @param param :  parameter passed to function
  * @desc genericGet($key,$compareField,$returnField,$table) :  put function description here ...
  */
 function genericGet($key, $compareField, $returnField, $table)
 {
     global $db;
     // Query to get $returnfield data based on $key
     $query = "select {$returnField} from {$table} where {$compareField}='{$key}'";
     $thisDatabaseQuery = new databaseQuery();
     $thisDatabaseQuery->setSqlQuery($query);
     $thisDatabaseQuery->executeQuery();
     $result = $thisDatabaseQuery->getResultSet();
     if ($result == false) {
         handleError("A Database Error Occured ", $db->ErrorMsg(), $_SERVER['PHP_SELF'], 'y', 'y');
     } else {
         if ($result->RowCount() == 0) {
             return "";
         } else {
             if ($result->RowCount() > 0) {
                 return $result->fields[$returnField];
             }
         }
     }
 }
function setSummoner($summonerName, $server)
{
    global $apiKey, $playerID, $name, $iconID, $level, $playerServer, $rankedLeague, $rankedTier;
    $playerServer = $server;
    $summonerName = str_replace(' ', '', $summonerName);
    // So if the user has spaces in it, it works.
    $url = 'https://' . $server . '.api.pvp.net/api/lol/' . $server . '/v1.4/summoner/by-name/' . $summonerName . '?api_key=' . $apiKey;
    $response = @file_get_contents($url);
    if (requestFailed($response, $url)) {
        $error = error_get_last();
        $error = $error['message'];
        $errorCode = substr($error, strpos($error, "/1.1") + 5, 3);
        handleError($errorCode, $url, "name and playerID");
        return;
    }
    $stats = json_decode($response)->{$summonerName};
    $playerID = $stats->id;
    $name = $stats->name;
    $iconID = $stats->profileIconId;
    $level = $stats->summonerLevel;
    $url = 'https://' . $playerServer . '.api.pvp.net/api/lol/' . $playerServer . '/v2.5/league/by-summoner/' . $playerID . '?api_key=' . $apiKey;
    $response = @file_get_contents($url);
    if (requestFailed($response, $url)) {
        $error = error_get_last();
        $error = $error['message'];
        $errorCode = substr($error, strpos($error, "/1.1") + 5, 3);
        if ($errorCode == "404" || $errorCode == "503") {
            handleError(405, $url, "league and tier");
        } else {
            handleError($errorCode, $url, "league and tier");
        }
        return;
    }
    $league = json_decode($response)->{$playerID};
    $rankedLeague = $league[0]->name;
    $rankedTier = $league[0]->tier;
}
Example #14
0
/**
 * @param mysqli $db
 * @param string $error
 * @param int $code
 * @param string $status
 */
function dbError($db, $error = "Database error", $code = 500, $status = "Server error")
{
    $dberror = $db->error;
    $db->rollback();
    $db->close();
    handleError($error . ': ' . $dberror);
}
Example #15
0
}
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'] . '/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "items")) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED;
    //not allowed page
    handleError('Not allowed to ...', 110);
    exit;
}
//check for session
if (isset($_POST['PHPSESSID'])) {
    session_id($_POST['PHPSESSID']);
} elseif (isset($_GET['PHPSESSID'])) {
    session_id($_GET['PHPSESSID']);
} else {
    handleError('No Session was found.');
}
// HTTP headers for no cache etc
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
if (isset($_POST["type_upload"]) && $_POST["type_upload"] == "upload_profile_photo") {
    $targetDir = $_SESSION['settings']['cpassman_dir'] . '/includes/avatars';
} else {
    $targetDir = $_SESSION['settings']['path_to_files_folder'];
}
$cleanupTargetDir = true;
// Remove old files
$maxFileAge = 5 * 3600;
//i_j_same_col = number of juveniles found with host-associate combination (>2 = medium)
//h_voucher = if specimen is a vouchered field host (>1 = medium)
//coll_percent = percent of total collecting events collected on that host genus (weigh this?)(>50% high)
//coll_total_i = number of total collecting events for that species, where a host was recorded
//h_n_specimens = count of max number of specimens found on a single collecting event with host/insect combination (>10 = high)
//insert confidence values into rel_confidence field: HIGH, MEDIUM, LOW
//export echo "select * from host_network_species" | mysql -u root -p -D AOE > plantHostsAllData.tsv
require_once "MDB2.php";
// === change this to run from your database credentials ===
##add conector
require_once "../../../../UniversalConnector.php";
#require_once("../../../UniversalConnector.php");
// === Main database connection and error handling ===
$DB =& MDB2::connect($dsn);
if (PEAR::isError($DB)) {
    handleError($DB->getMessage());
}
$unique_associations = find_stuff_out();
while ($row =& $unique_associations->fetchRow()) {
    $id = $row[0];
    $coll_number_same_h = $row[16];
    $coll_percent = $row[17];
    $rel_confidence = $row[22];
    is_high_medium_low($coll_percent, $id, $coll_number_same_h, $rel_confidence);
}
$higher_resolution = find_stuff_out_higher();
while ($row =& $higher_resolution->fetchRow()) {
    $count_medium = $row[0];
    $insect = $row[1];
    $i_species_id = $row[2];
    echo $count_medium . " " . $insect . " " . $i_species_id . "\n";
Example #17
0
handleError($result);
$query = "INSERT INTO booking VALUES('false', 'Anthony Kumar', '3');";
$result = pg_query($query);
handleError($result);
$query = "INSERT INTO booking VALUES('true', 'Faizal Rahul', '4');";
$result = pg_query($query);
handleError($result);
$query = "INSERT INTO booking VALUES('true', 'Ash Crater', '4');";
$result = pg_query($query);
handleError($result);
$query = "INSERT INTO booking VALUES('true', 'Hibari Kyoya', '4');";
$result = pg_query($query);
handleError($result);
$query = "INSERT INTO booking VALUES('true', 'Chen Qi Ting', '4');";
$result = pg_query($query);
handleError($result);
echo "booking table successfully populated.<br>";
pg_free_result($result);
pg_close($dbconn);
function handleError($result)
{
    if (!$result) {
        $errormessage = pg_last_error();
        echo "Error with query: " . $errormessage;
        exit;
    }
    return;
}
?>
 
Example #18
0
 function getListSelect()
 {
     global $gorumroll, $subscription_typ, $gorumuser;
     hasAdminRights($isAdm);
     if ($gorumroll->list == "subscription" || $gorumroll->list == "subscription_unsub") {
         if (!$isAdm) {
             handleError("Permission denied");
         }
         $select = "SELECT s.*, c.wholeName AS catName, c.permaLink AS catPermaLink, u.name AS userName, IF(u.id, u.email, s.email) AS email " . "FROM @subscription AS s LEFT JOIN @user AS u " . "ON s.uid=u.id LEFT JOIN @category AS c ON c.id=s.cid WHERE unsub=";
         $select .= $gorumroll->list == "subscription_unsub" ? "1" : "0";
         $subscription_typ["attributes"]["userName"][] = "list";
         $subscription_typ["attributes"]["email"][] = "list";
         $subscription_typ["attributes"]["catName"][] = "list";
     } elseif ($gorumroll->list == "subscription_cat") {
         if (!$isAdm) {
             handleError("Permission denied");
         }
         $select = array("SELECT s.*, u.name AS userName " . "FROM @subscription AS s LEFT JOIN @user AS u " . "ON s.uid=u.id WHERE cid=#rollid#", $gorumroll->rollid);
         $subscription_typ["attributes"]["userName"][] = "list";
         $subscription_typ["attributes"]["email"][] = "list";
     } elseif ($gorumroll->list == "subscription_my") {
         $select = array("SELECT s.*, c.wholeName AS catName, c.permaLink AS catPermaLink " . "FROM @subscription AS s, @category AS c " . "WHERE c.id=s.cid AND uid=#gorumuser->id#", $gorumuser->id);
         $subscription_typ["attributes"]["catName"][] = "list";
     }
     return $select;
 }
Example #19
0
     /* Not processed. */
     $pc = new SimpleSAML_Auth_ProcessingChain($idpmetadata, $spmetadata, 'idp');
     $authProcState = array('core:saml20-idp:requestcache' => $requestcache, 'ReturnURL' => SimpleSAML_Utilities::selfURLNoQuery(), 'Attributes' => $attributes, 'Destination' => $spmetadata, 'Source' => $idpmetadata, 'isPassive' => $isPassive, SimpleSAML_Auth_State::EXCEPTION_HANDLER_URL => SimpleSAML_Utilities::selfURLNoQuery());
     /*
      * Check whether the user has been authenticated to this SP previously
      * during this session. If the SP is authenticated earlier, we include
      * the timestamp to the authentication processing filters.
      */
     $previousSSOTime = $session->getData('saml2-idp-ssotime', $spentityid);
     if ($previousSSOTime !== NULL) {
         $authProcState['PreviousSSOTimestamp'] = $previousSSOTime;
     }
     try {
         $pc->processState($authProcState);
     } catch (Exception $e) {
         handleError($e);
     }
     $requestcache['AuthProcState'] = $authProcState;
 }
 $attributes = $authProcState['Attributes'];
 /*
  * Save the time we authenticated to this SP. This can be used later to detect an
  * SP which reauthenticates a user very often.
  */
 $session->setData('saml2-idp-ssotime', $spentityid, time(), SimpleSAML_Session::DATA_TIMEOUT_LOGOUT);
 // Adding this service provider to the list of sessions.
 // Right now the list is used for SAML 2.0 only.
 $session->add_sp_session($spentityid);
 $requestID = NULL;
 $relayState = NULL;
 if (array_key_exists('RequestID', $requestcache)) {
Example #20
0
/**
 * Update the credentials for the given user.
 * @author pdvrieze
 * @param mysqli $db The database connection.
 * @param string $user The user whose password to update.
 * @param string $newpassword The new password
 */
function updateCredentials($db, $user, $newpassword)
{
    $passwordhash = createPasswordHash($password);
    if ($stmt = $db->prepare('UPDATE `users` SET `password` = ? WHERE `user` = ?')) {
        if (!$stmt->bind_param("ss", $passwordhash, $user)) {
            handleError($db->error);
        }
        if ($stmt->execute() !== False) {
            $db->commit();
            return TRUE;
        } else {
            $db->rollback();
            handleError("Error updating password");
        }
    }
}
Example #21
0
/**
 * Returns the k_id of a keyword.
 *
 * Inserts a new record in the keyword table if it does not exist.
 *
 * @param string $keyword Keyword to get database ID for
 * @param PDO    $db      Database connection object
 *
 * @return integer|boolean Database ID of keyword, false on error
 */
function getKeywordId($keyword, $db)
{
    $stmt = $db->prepare('SELECT k_id FROM keywords WHERE k_keyword = :keyword');
    $ok = $stmt->execute(array(':keyword' => $keyword));
    if ($ok === false) {
        handleError($stmt);
        return false;
    }
    $arRow = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($arRow !== false) {
        return (int) $arRow['k_id'];
    }
    $stmt = $db->prepare('INSERT INTO keywords SET k_keyword = :keyword');
    $ok = $stmt->execute(array(':keyword' => $keyword));
    if ($ok === false) {
        handleError($stmt);
        return false;
    }
    return (int) $db->lastInsertId();
}
 function Connect($_data, $_action)
 {
     if (function_exists("gzuncompress")) {
         $_data["p_zip"] = "1";
     }
     $opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query($_data)));
     $context = stream_context_create($opts);
     $result = file_get_contents(CONFIG_LIVEZILLA_SOCIAL . strtolower(SocialMediaChannel::GetChannelTypeName($this->Type)) . "/?a=" . $_action, false, $context);
     if (!empty($result) && !empty($_data["p_zip"])) {
         $result = gzuncompress(base64_decode($result));
     }
     if (!empty($result) && is_string(json_decode($result)) && strpos(json_decode($result), "ERR") === 0) {
         handleError("123", "Error connecting social channel: " . $this->Name . " (" . json_decode($result) . ")", "", 0);
     } else {
         return $result;
     }
     return "";
 }
Example #23
0
 function validMedia($attr)
 {
     if (!isset($_FILES[$attr]["name"]) || $_FILES[$attr]["name"] == "") {
         return;
     }
     if ($_FILES[$attr]["size"] == 0) {
         return Roll::setFormInvalid("picFileSizeNull");
     }
     if ($_FILES[$attr]["tmp_name"] == "none") {
         return Roll::setFormInvalid("picFileSizeToLarge1");
     }
     $_S =& new AppSettings();
     if ($_S->maxMediaSize && $_FILES[$attr]["size"] > $_S->maxMediaSize) {
         return Roll::setFormInvalid("picFileSizeToLarge2", $_S->maxMediaSize);
     }
     if (!is_uploaded_file($_FILES[$attr]["tmp_name"])) {
         handleError("Possible attack");
     }
 }
* Example of PARTNER Weather station API
* If you need more details, please take a glance at https://dev.netatmo.com/doc
*/
define('__ROOT__', dirname(dirname(__FILE__)));
require_once __ROOT__ . '/src/Netatmo/autoload.php';
require_once 'Utils.php';
require_once 'Config.php';
//App client configuration
$config = array("client_id" => $client_id, "client_secret" => $client_secret, "username" => $test_username, "password" => $test_password);
$client = new Netatmo\Clients\NAWSApiClient($config);
//Authentication with Netatmo server (OAuth2)
try {
    $tokens = $client->getAccessToken();
} catch (Netatmo\Exceptions\NAClientException $ex) {
    handleError("An error happened while trying to retrieve your tokens: " . $ex->getMessage() . "\n", TRUE);
}
try {
    $deviceList = $client->getPartnerDevices();
} catch (Netatmo\Exceptions\NAClientException $ex) {
    handleError("An error occured while retrieving device list: " . $ex->getMessage() . "\n", TRUE);
}
if (!isset($deviceList['weather_stations']) || empty($deviceList['weather_stations'])) {
    echo "No Weather stations affiliated to partner app";
} else {
    try {
        $data = $client->getData($deviceList['weather_stations'][0]);
        printWSBasicInfo($data['devices'][0]);
    } catch (Netatmo\Exceptions\NAClientException $ex) {
        handleError("An error occured while retrieving device data " . $ex->getMessage() . "\n", TRUE);
    }
}
 private function SEND_SMTP_ZEND()
 {
     try {
         loadLibrary("ZEND", "Zend_Mail");
         loadLibrary("ZEND", "Zend_Mail_Transport_Smtp");
         if (empty($this->MailText)) {
             $this->MailText = ">>";
         }
         if ($this->Account->Authentication == "No") {
             $config = array('port' => $this->Account->Port);
         } else {
             $config = array('auth' => 'login', 'username' => $this->Account->Username, 'password' => $this->Account->Password, 'port' => $this->Account->Port);
         }
         if (!empty($this->Account->SSL)) {
             $config['ssl'] = $this->Account->SSL == 1 ? 'SSL' : 'TLS';
         }
         $transport = new Zend_Mail_Transport_Smtp($this->Account->Host, $config);
         $mail = new Zend_Mail('UTF-8');
         $mail->setBodyText($this->MailText);
         if (empty($this->FakeSender)) {
             $mail->setFrom($this->Account->Email, $this->Account->SenderName);
         } else {
             $mail->setFrom($this->FakeSender, $this->FakeSender);
         }
         if (strpos($this->Receiver, ",") !== false) {
             $emails = explode(",", $this->Receiver);
             $add = false;
             foreach ($emails as $mailrec) {
                 if (!empty($mailrec)) {
                     if (!$add) {
                         $add = true;
                         $mail->addTo($mailrec, $mailrec);
                     } else {
                         $mail->addBcc($mailrec, $mailrec);
                     }
                 }
             }
         } else {
             $mail->addTo($this->Receiver, $this->Receiver);
         }
         $mail->setSubject($this->Subject);
         $mail->setReplyTo($this->ReplyTo, $name = null);
         if ($this->Attachments != null) {
             foreach ($this->Attachments as $resId) {
                 $res = getResource($resId);
                 $at = $mail->createAttachment(file_get_contents("./uploads/" . $res["value"]));
                 $at->type = 'application/octet-stream';
                 $at->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
                 $at->encoding = Zend_Mime::ENCODING_BASE64;
                 $at->filename = $res["title"];
             }
         }
         $mail->send($transport);
     } catch (Exception $e) {
         if ($this->TestIt) {
             throw $e;
         } else {
             handleError("111", $this->Account->Host . " send mail connection error: " . $e->getMessage(), "functions.global.inc.php", 0);
         }
         return 0;
     }
     return 1;
 }
Example #26
0
    } else {
        $host = 'darwin.bournemouth.ac.uk';
        $secure = TRUE;
    }
    setrawcookie($DARWINCOOKIENAME, $authtoken, $cookieexpire, '/', $host, $secure);
    error_log(__FILE__ . ": Cookie set.");
    if (isset($_REQUEST['redirect'])) {
        error_log(__FILE__ . ": redirecting");
        header('Location: ' . $_REQUEST['redirect']);
        echo "Redirect!\n";
    } else {
        if ($htmloutput) {
            error_log(__FILE__ . ": Showing success screen");
            showSuccessScreen($_REQUEST['newuser']);
        } else {
            error_log(__FILE__ . ": Setting success");
            echo "login:"******"\n";
            for ($x = 0; $x < 0; $x++) {
                echo "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n";
            }
        }
    }
    error_log(__FILE__ . ": Cleaning tokens");
    $epoch = time();
    cleanTokens($db, $epoch);
    error_log(__FILE__ . ": Closing database");
    $db->close();
} else {
    error_log("Could not get database connection");
    handleError("Could not connect to the database");
}
Example #27
0
 function modifyForm()
 {
     global $gorumroll, $lll;
     $_EC = EComm::createObject();
     $this->id = $gorumroll->rollid;
     LocationHistory::saveGorumCategory($this->getCid());
     $this->activateVariableFields();
     //csak emiatt kellett feluldefinialn
     $this->initClassVars();
     if (!Roll::isPreviousFormSubmitInvalid()) {
         $ret = $this->load();
         if ($ret) {
             $txt = $lll["not_found_in_db"];
             handleError($txt);
         }
         $old =& $this;
     } else {
         G::load($old, $this->id, "item");
     }
     $this->hasObjectRights($hasRight, "modify", TRUE);
     if (isset($this->expirationTime) && !$this->expirationTime->isEmpty()) {
         $this->expiration = round($this->expirationTime->getDayDiff());
         if ($this->expirationTime->isPast()) {
             $this->expiration = "-{$this->expiration}";
         }
     }
     $this->addDeletePictureStuff();
     $this->addDeleteMediaStuff();
     $_EC->confirmRules($this->cid, $old);
     $this->cName = $this->getCatName();
     $this->catPermaLink = $this->getCatPermaLink();
     $this->generForm();
 }
Example #28
0
$pkg->setNotes($notes);
$pkg->setPackageType('php');
$pkg->setPhpDep('5.0.0');
$pkg->setPearinstallerDep('1.4.9');
// Require custom file role for our web installation
// $pkg->addPackageDepWithChannel('required', 'Role_Web', 'pearified.com');
// Define that we will use our custom file role in this script
// $pkg->addUsesRole('web', 'Webfiles');
// Create the current release and add it to the package definition
$pkg->addRelease();
handleError($pkg->generateContents());
// Package release needs a maintainer
foreach ($maintainers as $m) {
    handleError($pkg->addMaintainer($m[0], $m[1], $m[2], $m[3]));
}
if ($argv[1] === 'write') {
    handleError($pkg->writePackageFile());
    exit(1);
}
handleError($pkg->debugPackageFile());
/**
 * Simple error handler
 *
 * @param Exception $e
 */
function handleError($e)
{
    if (PEAR::isError($e)) {
        die($e->getMessage());
    }
}
Example #29
0
 function cacheFatherObjects()
 {
     global $fatherCatList;
     global $gorumroll;
     if ((!isset($this->id) || !$this->id) && $gorumroll->rollid) {
         $this->id = $gorumroll->rollid;
         $ret = load($this);
         if ($ret) {
             $txt = "can not load category object";
             handleError($txt);
         }
     }
     if (!isset($fatherCatList) || !$fatherCatList) {
         $fatherCatList = array();
         //if ($withOwn) $fatherCatList[] = $this;
         $childCat = gclone($this);
         while (!empty($childCat->up)) {
             G::load($childCat, $childCat->up, "appcategory");
             $fatherCatList[] = $childCat;
         }
         $fatherCatList = array_reverse($fatherCatList);
     }
 }
Example #30
0
function handleFatal()
{
    $error = error_get_last();
    if ($error['type'] == E_ERROR) {
        handleError($error['type'], $error['message'], $error['file'], $error['line']);
    }
}