Ejemplo n.º 1
0
 public function run()
 {
     if (YII_DEBUG && in_array(getIPAddress(), array("127.0.0.1", "::1"))) {
         $data = array('session' => $_SESSION, 'server' => $_SERVER);
         $json = json_encode($data, JSON_FORCE_OBJECT);
         $script = "LSdebug = {$json};\n";
         $script .= "console.dir(LSdebug)\n";
         App()->getClientScript()->registerScript('LimeDebug', $script, CClientScript::POS_HEAD);
     }
 }
Ejemplo n.º 2
0
 public function run()
 {
     if (YII_DEBUG && in_array(getIPAddress(), array("127.0.0.1", "::1"))) {
         //App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish(Yii::getPathOfAlias('ext.LimeScript.assets'). '/script.js'));
         $data = array('session' => $_SESSION, 'server' => $_SERVER);
         $json = json_encode($data, JSON_FORCE_OBJECT);
         $script = "LSdebug = {$json};\n";
         $script .= "console.dir(LSdebug)\n";
         App()->getClientScript()->registerScript('LimeDebug', $script, CClientScript::POS_HEAD);
     }
 }
Ejemplo n.º 3
0
 public function authenticate()
 {
     // First initialize the result, we can later retieve it to get the exact error code/message
     $result = new LSAuthResult(self::ERROR_NONE);
     // Check if the ip is locked out
     if (FailedLoginAttempt::model()->isLockedOut()) {
         $message = sprintf(gT('You have exceeded the number of maximum login attempts. Please wait %d minutes before trying again.'), App()->getConfig('timeOutTime') / 60);
         $result->setError(self::ERROR_IP_LOCKED_OUT, $message);
     }
     // If still ok, continue
     if ($result->isValid()) {
         if (is_null($this->plugin)) {
             $result->setError(self::ERROR_UNKNOWN_HANDLER);
         } else {
             // Delegate actual authentication to plugin
             $authEvent = new PluginEvent('newUserSession', $this);
             $authEvent->set('identity', $this);
             App()->getPluginManager()->dispatchEvent($authEvent);
             $pluginResult = $authEvent->get('result');
             if ($pluginResult instanceof LSAuthResult) {
                 $result = $pluginResult;
             } else {
                 $result->setError(self::ERROR_UNKNOWN_IDENTITY);
             }
         }
     }
     if ($result->isValid()) {
         // Perform postlogin
         $this->postLogin();
     } else {
         // Log a failed attempt
         $userHostAddress = getIPAddress();
         FailedLoginAttempt::model()->addAttempt($userHostAddress);
         App()->session->regenerateID();
         // Handled on login by Yii
     }
     $this->errorCode = $result->getCode();
     $this->errorMessage = $result->getMessage();
     return $result->isValid();
 }
Ejemplo n.º 4
0
function savedcontrol()
{
    //This data will be saved to the "saved_control" table with one row per response.
    // - a unique "saved_id" value (autoincremented)
    // - the "sid" for this survey
    // - the "srid" for the survey_x row id
    // - "saved_thisstep" which is the step the user is up to in this survey
    // - "saved_ip" which is the ip address of the submitter
    // - "saved_date" which is the date ofthe saved response
    // - an "identifier" which is like a username
    // - a "password"
    // - "fieldname" which is the fieldname of the saved response
    // - "value" which is the value of the response
    //We start by generating the first 5 values which are consistent for all rows.
    global $connect, $surveyid, $dbprefix, $thissurvey, $errormsg, $publicurl, $sitename, $timeadjust, $clang, $clienttoken, $thisstep;
    //Check that the required fields have been completed.
    $errormsg = "";
    /* queXS Removal
    
            if (!isset($_POST['savename']) || !$_POST['savename']) {$errormsg.=$clang->gT("You must supply a name for this saved session.")."<br />\n";}
            if (!isset($_POST['savepass']) || !$_POST['savepass']) {$errormsg.=$clang->gT("You must supply a password for this saved session.")."<br />\n";}
            if ((isset($_POST['savepass']) && !isset($_POST['savepass2'])) || $_POST['savepass'] != $_POST['savepass2'])
            {$errormsg.=$clang->gT("Your passwords do not match.")."<br />\n";}
            // if security question asnwer is incorrect
            if (function_exists("ImageCreate") && captcha_enabled('saveandloadscreen',$thissurvey['usecaptcha']))
            {
                if (!isset($_POST['loadsecurity']) ||
                !isset($_SESSION['secanswer']) ||
                $_POST['loadsecurity'] != $_SESSION['secanswer'])
                {
                    $errormsg .= $clang->gT("The answer to the security question is incorrect.")."<br />\n";
                }
            }
    
            if (trim($_POST['saveemail'])!='' && !validate_email($_POST['saveemail']))
            {
                $errormsg .= $clang->gT("The email address is not valid. Please leave the email field blank or give a valid email address.")."<br />\n";
            }
    
    	end queXS Removal */
    if ($errormsg) {
        return;
    }
    //All the fields are correct. Now make sure there's not already a matching saved item
    $query = "SELECT COUNT(*) FROM {$dbprefix}saved_control\n" . "WHERE sid={$surveyid}\n" . "AND identifier=" . db_quoteall($_POST['token'], true);
    $result = db_execute_num($query) or safe_die("Error checking for duplicates!<br />{$query}<br />" . $connect->ErrorMsg());
    // Checked
    list($count) = $result->FetchRow();
    if ($count == 1) {
        //we should update the field with the latest $_SESSION['step'] - stored in saved_thisstep - queXS addition
        $sql = "UPDATE {$dbprefix}saved_control SET saved_thisstep = '{$_SESSION['step']}' WHERE sid={$surveyid} AND identifier='{$_POST['token']}'";
        $connect->Execute($sql);
    } else {
        if ($count > 0) {
            $errormsg .= $clang->gT("This name has already been used for this survey. You must use a unique save name.") . "<br />\n";
            return;
        } else {
            //INSERT BLANK RECORD INTO "survey_x" if one doesn't already exist
            if (!isset($_SESSION['srid'])) {
                $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
                $sdata = array("datestamp" => $today, "ipaddr" => getIPAddress(), "startlanguage" => $_SESSION['s_lang'], "refurl" => getenv("HTTP_REFERER"), "token" => $_POST['token']);
                //One of the strengths of ADOdb's AutoExecute() is that only valid field names for $table are updated
                if ($connect->AutoExecute($thissurvey['tablename'], $sdata, 'INSERT')) {
                    $srid = $connect->Insert_ID($thissurvey['tablename'], "sid");
                    $_SESSION['srid'] = $srid;
                } else {
                    safe_die("Unable to insert record into survey table.<br /><br />" . $connect->ErrorMsg());
                }
            }
            //CREATE ENTRY INTO "saved_control"
            $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
            $scdata = array("sid" => $surveyid, "srid" => $_SESSION['srid'], "identifier" => $_POST['token'], "access_code" => md5($_POST['token']), "email" => $_POST['token'], "ip" => getIPAddress(), "refurl" => getenv("HTTP_REFERER"), "saved_thisstep" => $thisstep, "status" => "S", "saved_date" => $today);
            if ($connect->AutoExecute("{$dbprefix}saved_control", $scdata, 'INSERT')) {
                $scid = $connect->Insert_ID("{$dbprefix}saved_control", 'scid');
                $_SESSION['scid'] = $scid;
            } else {
                safe_die("Unable to insert record into saved_control table.<br /><br />" . $connect->ErrorMsg());
            }
            $_SESSION['holdname'] = $_POST['token'];
            //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output
            $_SESSION['holdpass'] = $_POST['token'];
            //Session variable used to load answers every page.  Unsafe - so it has to be taken care of on output
            /* queXS Removal
            
                        //Email if needed
                        if (isset($_POST['saveemail']) && validate_email($_POST['saveemail']))
                        {
                            $subject=$clang->gT("Saved Survey Details") . " - " . $thissurvey['name'];
                            $message=$clang->gT("Thank you for saving your survey in progress.  The following details can be used to return to this survey and continue where you left off.  Please keep this e-mail for your reference - we cannot retrieve the password for you.","unescaped");
                            $message.="\n\n".$thissurvey['name']."\n\n";
                            $message.=$clang->gT("Name","unescaped").": ".$_POST['savename']."\n";
                            $message.=$clang->gT("Password","unescaped").": ".$_POST['savepass']."\n\n";
                            $message.=$clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):","unescaped")."\n";
                            $message.=$publicurl."/index.php?sid=$surveyid&loadall=reload&scid=".$scid."&loadname=".urlencode($_POST['savename'])."&loadpass="******"&token=".$clienttoken;}
                            $from="{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
                            if (SendEmailMessage(null, $message, $subject, $_POST['saveemail'], $from, $sitename, false, getBounceEmail($surveyid)))
                            {
                                $emailsent="Y";
                            }
                            else
                            {
                                echo $clang->gT('Error: Email failed, this may indicate a PHP Mail Setup problem on the server. Your survey details have still been saved, however you will not get an email with the details. You should note the "name" and "password" you just used for future reference.');
                            }
                        }
            
            		end queXS Removal */
            return $clang->gT('Your survey was successfully saved.');
        }
    }
}
 /**
  * Write values to database.
  * @param <type> $updatedValues
  * @param <boolean> $finished - true if the survey needs to be finalized
  */
 private function _UpdateValuesInDatabase($updatedValues, $finished = false)
 {
     //  TODO - now that using $this->updatedValues, may be able to remove local copies of it (unless needed by other sub-systems)
     $updatedValues = $this->updatedValues;
     $message = '';
     if (!$this->surveyOptions['active'] || $this->sPreviewMode) {
         return $message;
     }
     if (!isset($_SESSION[$this->sessid]['srid'])) {
         $_SESSION[$this->sessid]['datestamp'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
         // Create initial insert row for this record
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
         $sdata = array("startlanguage" => $this->surveyOptions['startlanguage']);
         if ($this->surveyOptions['anonymized'] == false) {
             $sdata['token'] = $this->surveyOptions['token'];
         }
         if ($this->surveyOptions['datestamp'] == true) {
             $sdata['datestamp'] = $_SESSION[$this->sessid]['datestamp'];
             $sdata['startdate'] = $_SESSION[$this->sessid]['datestamp'];
         }
         if ($this->surveyOptions['ipaddr'] == true) {
             $sdata['ipaddr'] = getIPAddress();
         }
         if ($this->surveyOptions['refurl'] == true) {
             if (isset($_SESSION[$this->sessid]['refurl'])) {
                 $sdata['refurl'] = $_SESSION[$this->sessid]['refurl'];
             } else {
                 $sdata['refurl'] = getenv("HTTP_REFERER");
             }
         }
         $sdata = array_filter($sdata);
         SurveyDynamic::sid($this->sid);
         $oSurvey = new SurveyDynamic();
         $iNewID = $oSurvey->insertRecords($sdata);
         if ($iNewID) {
             $srid = $iNewID;
             $_SESSION[$this->sessid]['srid'] = $iNewID;
         } else {
             $message .= $this->gT("Unable to insert record into survey table");
             // TODO - add SQL error?
             echo submitfailed('');
             // TODO - report SQL error?
         }
         //Insert Row for Timings, if needed
         if ($this->surveyOptions['savetimings']) {
             SurveyTimingDynamic::sid($this->sid);
             $oSurveyTimings = new SurveyTimingDynamic();
             $tdata = array('id' => $srid, 'interviewtime' => 0);
             switchMSSQLIdentityInsert("survey_{$this->sid}_timings", true);
             $iNewID = $oSurveyTimings->insertRecords($tdata);
             switchMSSQLIdentityInsert("survey_{$this->sid}_timings", false);
         }
     }
     if (count($updatedValues) > 0 || $finished) {
         $query = 'UPDATE ' . $this->surveyOptions['tablename'] . ' SET ';
         $setter = array();
         switch ($this->surveyMode) {
             case 'question':
                 $thisstep = $this->currentQuestionSeq;
                 break;
             case 'group':
                 $thisstep = $this->currentGroupSeq;
                 break;
             case 'survey':
                 $thisstep = 1;
                 break;
         }
         $setter[] = dbQuoteID('lastpage') . "=" . dbQuoteAll($thisstep);
         if ($this->surveyOptions['datestamp'] && isset($_SESSION[$this->sessid]['datestamp'])) {
             $_SESSION[$this->sessid]['datestamp'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
             $setter[] = dbQuoteID('datestamp') . "=" . dbQuoteAll(dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']));
         }
         if ($this->surveyOptions['ipaddr']) {
             $setter[] = dbQuoteID('ipaddr') . "=" . dbQuoteAll(getIPAddress());
         }
         foreach ($updatedValues as $key => $value) {
             $val = is_null($value) ? NULL : $value['value'];
             $type = is_null($value) ? NULL : $value['type'];
             // Clean up the values to cope with database storage requirements
             switch ($type) {
                 case 'D':
                     //DATE
                     if (trim($val) == '' || $val == "INVALID") {
                         $val = NULL;
                         // since some databases can't store blanks in date fields
                     }
                     // otherwise will already be in yyyy-mm-dd format after ProcessCurrentResponses()
                     break;
                 case '|':
                     //File upload
                     // This block can be removed once we require 5.3 or later
                     if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
                         $val = addslashes($val);
                     }
                     break;
                 case 'N':
                     //NUMERICAL QUESTION TYPE
                 //NUMERICAL QUESTION TYPE
                 case 'K':
                     //MULTIPLE NUMERICAL QUESTION
                     if (trim($val) == '') {
                         $val = NULL;
                         // since some databases can't store blanks in numerical inputs
                     }
                     break;
                 default:
                     break;
             }
             if (is_null($val)) {
                 $setter[] = dbQuoteID($key) . "=NULL";
             } else {
                 $setter[] = dbQuoteID($key) . "=" . dbQuoteAll($val);
             }
         }
         $query .= implode(', ', $setter);
         $query .= " WHERE ID=";
         if (isset($_SESSION[$this->sessid]['srid']) && $this->surveyOptions['active']) {
             $query .= $_SESSION[$this->sessid]['srid'];
             if (!dbExecuteAssoc($query)) {
                 echo submitfailed('');
                 // TODO - report SQL error?
                 if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                     $message .= $this->gT('Error in SQL update');
                     // TODO - add  SQL error?
                 }
             } elseif ($this->surveyOptions['savetimings']) {
                 Yii::import("application.libraries.Save");
                 $cSave = new Save();
                 $cSave->set_answer_time();
             }
             if ($finished) {
                 // Delete the save control record if successfully finalize the submission
                 $query = "DELETE FROM {{saved_control}} where srid=" . $_SESSION[$this->sessid]['srid'] . ' and sid=' . $this->sid;
                 Yii::app()->db->createCommand($query)->execute();
                 if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                     $message .= ';<br />' . $query;
                 }
             } else {
                 if ($this->surveyOptions['allowsave'] && isset($_SESSION[$this->sessid]['scid'])) {
                     SavedControl::model()->updateByPk($_SESSION[$this->sessid]['scid'], array('saved_thisstep' => $thisstep));
                 }
             }
             // Check Quotas
             $aQuotas = checkCompletedQuota($this->sid, 'return');
             if ($aQuotas && !empty($aQuotas)) {
                 checkCompletedQuota($this->sid);
                 // will create a page and quit: why not use it directly ?
             } else {
                 if ($finished) {
                     $sQuery = 'UPDATE ' . $this->surveyOptions['tablename'] . " SET ";
                     if ($this->surveyOptions['datestamp']) {
                         // Replace with date("Y-m-d H:i:s") ? See timeadjust
                         $sQuery .= dbQuoteID('submitdate') . "=" . dbQuoteAll(dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']));
                     } else {
                         $sQuery .= dbQuoteID('submitdate') . "=" . dbQuoteAll(date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980)));
                     }
                     $sQuery .= " WHERE ID=" . $_SESSION[$this->sessid]['srid'];
                     dbExecuteAssoc($sQuery);
                     // Checked
                 }
             }
         }
         if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
             $message .= $query;
         }
     }
     return $message;
 }
Ejemplo n.º 6
0
function do_shortfreetext($ia)
{
    global $thissurvey;
    $sGoogleMapsAPIKey = trim(Yii::app()->getConfig("googleMapsAPIKey"));
    if ($sGoogleMapsAPIKey != '') {
        $sGoogleMapsAPIKey = '&key=' . $sGoogleMapsAPIKey;
    }
    $extraclass = "";
    $aQuestionAttributes = QuestionAttribute::model()->getQuestionAttributes($ia[0]);
    if ($aQuestionAttributes['numbers_only'] == 1) {
        $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
        $sSeparator = $sSeparator['separator'];
        $extraclass .= " numberonly";
        $checkconditionFunction = "fixnum_checkconditions";
    } else {
        $checkconditionFunction = "checkconditions";
    }
    if (intval(trim($aQuestionAttributes['maximum_chars'])) > 0) {
        // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea
        $maximum_chars = intval(trim($aQuestionAttributes['maximum_chars']));
        $maxlength = "maxlength='{$maximum_chars}' ";
        $extraclass .= " maxchars maxchars-" . $maximum_chars;
    } else {
        $maxlength = "";
    }
    if (trim($aQuestionAttributes['text_input_width']) != '') {
        $tiwidth = $aQuestionAttributes['text_input_width'];
        $extraclass .= " inputwidth-" . trim($aQuestionAttributes['text_input_width']);
        $col = $aQuestionAttributes['text_input_width'] <= 12 ? $aQuestionAttributes['text_input_width'] : 12;
        $extraclass .= " col-sm-" . trim($col);
    } else {
        $tiwidth = 50;
    }
    if (trim($aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $prefix = $aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
        $extraclass .= " withprefix";
    } else {
        $prefix = '';
    }
    if (trim($aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $suffix = $aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
        $extraclass .= " withsuffix";
    } else {
        $suffix = '';
    }
    if ($thissurvey['nokeyboard'] == 'Y') {
        includeKeypad();
        $kpclass = "text-keypad";
        $extraclass .= " inputkeypad";
    } else {
        $kpclass = "";
    }
    $answer = "";
    if (trim($aQuestionAttributes['display_rows']) != '') {
        //question attribute "display_rows" is set -> we need a textarea to be able to show several rows
        $drows = $aQuestionAttributes['display_rows'];
        //if a textarea should be displayed we make it equal width to the long text question
        //this looks nicer and more continuous
        if ($tiwidth == 50) {
            $tiwidth = 40;
        }
        $dispVal = "";
        if ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]) {
            $dispVal = str_replace("\\", "", $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]);
            if ($aQuestionAttributes['numbers_only'] == 1) {
                $dispVal = str_replace('.', $sSeparator, $dispVal);
            }
            $dispVal = htmlspecialchars($dispVal);
        }
        $answer .= doRender('/survey/questions/shortfreetext/textarea/item', array('extraclass' => $extraclass, 'freeTextId' => 'answer' . $ia[1], 'labelText' => gT('Your answer'), 'name' => $ia[1], 'drows' => $drows, 'tiwidth' => $tiwidth, 'checkconditionFunction' => $checkconditionFunction . '(this.value, this.name, this.type)', 'dispVal' => $dispVal, 'maxlength' => $maxlength, 'kpclass' => $kpclass, 'prefix' => $prefix, 'suffix' => $suffix, 'sm_col' => decide_sm_col($prefix, $suffix)), true);
    } elseif ((int) $aQuestionAttributes['location_mapservice'] == 1) {
        $mapservice = $aQuestionAttributes['location_mapservice'];
        $currentLocation = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]];
        $currentLatLong = null;
        $floatLat = 0;
        $floatLng = 0;
        // Get the latitude/longtitude for the point that needs to be displayed by default
        if (strlen($currentLocation) > 2) {
            $currentLatLong = explode(';', $currentLocation);
            $currentLatLong = array($currentLatLong[0], $currentLatLong[1]);
        } else {
            if ((int) $aQuestionAttributes['location_nodefaultfromip'] == 0) {
                $currentLatLong = getLatLongFromIp(getIPAddress());
            }
            if (!isset($currentLatLong) || $currentLatLong == false) {
                $floatLat = 0;
                $floatLng = 0;
                $LatLong = explode(" ", trim($aQuestionAttributes['location_defaultcoordinates']));
                if (isset($LatLong[0]) && isset($LatLong[1])) {
                    $floatLat = $LatLong[0];
                    $floatLng = $LatLong[1];
                }
                $currentLatLong = array($floatLat, $floatLng);
            }
        }
        // 2 - city; 3 - state; 4 - country; 5 - postal
        $strBuild = "";
        if ($aQuestionAttributes['location_city']) {
            $strBuild .= "2";
        }
        if ($aQuestionAttributes['location_state']) {
            $strBuild .= "3";
        }
        if ($aQuestionAttributes['location_country']) {
            $strBuild .= "4";
        }
        if ($aQuestionAttributes['location_postal']) {
            $strBuild .= "5";
        }
        $currentLocation = $currentLatLong[0] . " " . $currentLatLong[1];
        Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "map.js");
        if ($aQuestionAttributes['location_mapservice'] == 1 && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") {
            Yii::app()->getClientScript()->registerScriptFile("https://maps.googleapis.com/maps/api/js?sensor=false{$sGoogleMapsAPIKey}");
        } else {
            if ($aQuestionAttributes['location_mapservice'] == 1) {
                Yii::app()->getClientScript()->registerScriptFile("http://maps.googleapis.com/maps/api/js?sensor=false{$sGoogleMapsAPIKey}");
            } elseif ($aQuestionAttributes['location_mapservice'] == 2) {
                Yii::app()->getClientScript()->registerScriptFile("http://www.openlayers.org/api/OpenLayers.js");
            }
        }
        $questionHelp = false;
        if (isset($aQuestionAttributes['hide_tip']) && $aQuestionAttributes['hide_tip'] == 0) {
            $questionHelp = true;
            $question_text['help'] = gT('Drag and drop the pin to the desired location. You may also right click on the map to move the pin.');
        }
        $answer = doRender('/survey/questions/shortfreetext/location_mapservice/item', array('extraclass' => $extraclass, 'freeTextId' => 'answer' . $ia[1], 'labelText' => gT('Your answer'), 'name' => $ia[1], 'checkconditionFunction' => $checkconditionFunction . '(this.value, this.name, this.type)', 'value' => $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]], 'kpclass' => $kpclass, 'currentLocation' => $currentLocation, 'strBuild' => $strBuild, 'location_mapservice' => $aQuestionAttributes['location_mapservice'], 'location_mapzoom' => $aQuestionAttributes['location_mapzoom'], 'location_mapheight' => $aQuestionAttributes['location_mapheight'], 'questionHelp' => $questionHelp, 'question_text_help' => isset($question_text) ? $question_text['help'] : '', 'sm_col' => decide_sm_col($prefix, $suffix)), true);
    } elseif ((int) $aQuestionAttributes['location_mapservice'] == 100) {
        $currentLocation = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]];
        $currentCenter = $currentLatLong = null;
        // Get the latitude/longtitude for the point that needs to be displayed by default
        if (strlen($currentLocation) > 2 && strpos($currentLocation, ";")) {
            $currentLatLong = explode(';', $currentLocation);
            $currentCenter = $currentLatLong = array($currentLatLong[0], $currentLatLong[1]);
        } elseif ((int) $aQuestionAttributes['location_nodefaultfromip'] == 0) {
            $currentCenter = $currentLatLong = getLatLongFromIp(getIPAddress());
        }
        // If it's not set : set the center to the default position, but don't set the marker
        if (!$currentLatLong) {
            $currentLatLong = array("", "");
            $currentCenter = explode(" ", trim($aQuestionAttributes['location_defaultcoordinates']));
            if (count($currentCenter) != 2) {
                $currentCenter = array("", "");
            }
        }
        $strBuild = "";
        $aGlobalMapScriptVar = array('geonameUser' => getGlobalSetting('GeoNamesUsername'), 'geonameLang' => Yii::app()->language);
        $aThisMapScriptVar = array('zoomLevel' => $aQuestionAttributes['location_mapzoom'], 'latitude' => $currentCenter[0], 'longitude' => $currentCenter[1]);
        App()->getClientScript()->registerPackage('leaflet');
        Yii::app()->getClientScript()->registerScript('sGlobalMapScriptVar', "LSmap=" . ls_json_encode($aGlobalMapScriptVar) . ";\nLSmaps= new Array();", CClientScript::POS_HEAD);
        Yii::app()->getClientScript()->registerScript('sThisMapScriptVar' . $ia[1], "LSmaps['{$ia[1]}']=" . ls_json_encode($aThisMapScriptVar), CClientScript::POS_HEAD);
        Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "map.js");
        Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . 'map.css');
        if (isset($aQuestionAttributes['hide_tip']) && $aQuestionAttributes['hide_tip'] == 0) {
            $questionHelp = true;
            $question_text['help'] = gT('Click to set the location or drag and drop the pin. You may may also enter coordinates');
        }
        $itemDatas = array('extraclass' => $extraclass, 'name' => $ia[1], 'checkconditionFunction' => $checkconditionFunction . '(this.value, this.name, this.type)', 'value' => $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]], 'strBuild' => $strBuild, 'location_mapservice' => $aQuestionAttributes['location_mapservice'], 'location_mapzoom' => $aQuestionAttributes['location_mapzoom'], 'location_mapheight' => $aQuestionAttributes['location_mapheight'], 'questionHelp' => isset($questionHelp) ? $questionHelp : '', 'question_text_help' => $question_text['help'], 'location_value' => $currentLatLong[0] . ' ' . $currentLatLong[1], 'currentLat' => $currentLatLong[0], 'currentLong' => $currentLatLong[1]);
        $answer = doRender('/survey/questions/shortfreetext/location_mapservice/item_100', $itemDatas, true);
    } else {
        //no question attribute set, use common input text field
        $dispVal = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]];
        if ($aQuestionAttributes['numbers_only'] == 1) {
            $dispVal = str_replace('.', $sSeparator, $dispVal);
        }
        $dispVal = htmlspecialchars($dispVal, ENT_QUOTES, 'UTF-8');
        $itemDatas = array('extraclass' => $extraclass, 'name' => $ia[1], 'checkconditionFunction' => $checkconditionFunction . '(this.value, this.name, this.type)', 'prefix' => $prefix, 'suffix' => $suffix, 'kpclass' => $kpclass, 'tiwidth' => $tiwidth, 'dispVal' => $dispVal, 'maxlength' => $maxlength, 'sm_col' => decide_sm_col($prefix, $suffix));
        $answer = doRender('/survey/questions/shortfreetext/text/item', $itemDatas, true);
    }
    if (trim($aQuestionAttributes['time_limit']) != '') {
        $answer .= return_timer_script($aQuestionAttributes, $ia, "answer" . $ia[1]);
    }
    $inputnames = array();
    $inputnames[] = $ia[1];
    return array($answer, $inputnames);
}
Ejemplo n.º 7
0
 function savedcontrol()
 {
     //This data will be saved to the "saved_control" table with one row per response.
     // - a unique "saved_id" value (autoincremented)
     // - the "sid" for this survey
     // - the "srid" for the survey_x row id
     // - "saved_thisstep" which is the step the user is up to in this survey
     // - "saved_ip" which is the ip address of the submitter
     // - "saved_date" which is the date ofthe saved response
     // - an "identifier" which is like a username
     // - a "password"
     // - "fieldname" which is the fieldname of the saved response
     // - "value" which is the value of the response
     //We start by generating the first 5 values which are consistent for all rows.
     global $surveyid, $thissurvey, $errormsg, $publicurl, $sitename, $clang, $clienttoken, $thisstep;
     $timeadjust = getGlobalSetting('timeadjust');
     //Check that the required fields have been completed.
     $errormsg = '';
     if (empty($_POST['savename'])) {
         $errormsg .= $clang->gT("You must supply a name for this saved session.") . "<br />\n";
     }
     if (empty($_POST['savepass'])) {
         $errormsg .= $clang->gT("You must supply a password for this saved session.") . "<br />\n";
     }
     if (empty($_POST['savepass']) || empty($_POST['savepass2']) || $_POST['savepass'] != $_POST['savepass2']) {
         $errormsg .= $clang->gT("Your passwords do not match.") . "<br />\n";
     }
     // if security question asnwer is incorrect
     if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
         if (empty($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $_POST['loadsecurity'] != $_SESSION['survey_' . $surveyid]['secanswer']) {
             $errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
         }
     }
     if (!empty($errormsg)) {
         return;
     }
     $duplicate = SavedControl::model()->findByAttributes(array('sid' => $surveyid, 'identifier' => $_POST['savename']));
     if (!empty($duplicate) && $duplicate->count() > 0) {
         $errormsg .= $clang->gT("This name has already been used for this survey. You must use a unique save name.") . "<br />\n";
         return;
     } else {
         //INSERT BLANK RECORD INTO "survey_x" if one doesn't already exist
         if (!isset($_SESSION['survey_' . $surveyid]['srid'])) {
             $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
             $sdata = array("datestamp" => $today, "ipaddr" => getIPAddress(), "startlanguage" => $_SESSION['survey_' . $surveyid]['s_lang'], "refurl" => getenv("HTTP_REFERER"));
             if (SurveyDynamic::model($thissurvey['sid'])->insert($sdata)) {
                 $srid = getLastInsertID('{{survey_' . $surveyid . '}}');
                 $_SESSION['survey_' . $surveyid]['srid'] = $srid;
             } else {
                 safeDie("Unable to insert record into survey table.<br /><br />");
             }
         }
         //CREATE ENTRY INTO "saved_control"
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
         $saved_control = new SavedControl();
         $saved_control->sid = $surveyid;
         $saved_control->srid = $_SESSION['survey_' . $surveyid]['srid'];
         $saved_control->identifier = $_POST['savename'];
         // Binding does escape, so no quoting/escaping necessary
         $saved_control->access_code = md5($_POST['savepass']);
         $saved_control->email = $_POST['saveemail'];
         $saved_control->ip = getIPAddress();
         $saved_control->saved_thisstep = $thisstep;
         $saved_control->status = 'S';
         $saved_control->saved_date = $today;
         $saved_control->refurl = getenv('HTTP_REFERER');
         if ($saved_control->save()) {
             $scid = getLastInsertID('{{saved_control}}');
             $_SESSION['survey_' . $surveyid]['scid'] = $scid;
         } else {
             safeDie("Unable to insert record into saved_control table.<br /><br />");
         }
         $_SESSION['survey_' . $surveyid]['holdname'] = $_POST['savename'];
         //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output
         $_SESSION['survey_' . $surveyid]['holdpass'] = $_POST['savepass'];
         //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output
         //Email if needed
         if (isset($_POST['saveemail']) && validateEmailAddress($_POST['saveemail'])) {
             $subject = $clang->gT("Saved Survey Details") . " - " . $thissurvey['name'];
             $message = $clang->gT("Thank you for saving your survey in progress.  The following details can be used to return to this survey and continue where you left off.  Please keep this e-mail for your reference - we cannot retrieve the password for you.");
             $message .= "\n\n" . $thissurvey['name'] . "\n\n";
             $message .= $clang->gT("Name") . ": " . $_POST['savename'] . "\n";
             $message .= $clang->gT("Password") . ": " . $_POST['savepass'] . "\n\n";
             $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . "\n";
             $message .= Yii::app()->getController()->createAbsoluteUrl("/survey/index/sid/{$surveyid}/loadall/reload/scid/{$scid}/loadname/" . rawurlencode($_POST['savename']) . "/loadpass/" . rawurlencode($_POST['savepass']) . "/lang/" . rawurlencode($clang->langcode));
             if ($clienttoken) {
                 $message .= "/token/" . rawurlencode($clienttoken);
             }
             $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
             if (SendEmailMessage($message, $subject, $_POST['saveemail'], $from, $sitename, false, getBounceEmail($surveyid))) {
                 $emailsent = "Y";
             } else {
                 $errormsg .= $clang->gT('Error: Email failed, this may indicate a PHP Mail Setup problem on the server. Your survey details have still been saved, however you will not get an email with the details. You should note the "name" and "password" you just used for future reference.');
                 if (trim($thissurvey['adminemail']) == '') {
                     $errormsg .= $clang->gT('(Reason: Admin email address empty)');
                 }
             }
         }
         return $clang->gT('Your survey was successfully saved.');
     }
 }
Ejemplo n.º 8
0
             $utquery .= "SET usesleft=usesleft-1, completed='Y'\n";
         } else {
             $utquery .= "SET usesleft=usesleft-1\n";
         }
     }
     $utquery .= "WHERE token=" . db_quoteall($_POST['token'], true);
     $utresult = $connect->Execute($utquery) or safe_die("Couldn't update tokens table!<br />\n{$utquery}<br />\n" . $connect->ErrorMsg());
     // save submitdate into survey table
     $srid = $connect->Insert_ID();
     $sdquery = "UPDATE {$dbprefix}survey_{$surveyid} SET submitdate=" . db_quoteall($submitdate, true) . " WHERE id={$srid}\n";
     $sdresult = $connect->Execute($sdquery) or safe_die("Couldn't set submitdate response in survey table!<br />\n{$sdquery}<br />\n" . $connect->ErrorMsg());
 }
 if (isset($_POST['save']) && $_POST['save'] == "on") {
     $srid = $connect->Insert_ID();
     //CREATE ENTRY INTO "saved_control"
     $scdata = array("sid" => $surveyid, "srid" => $srid, "identifier" => $saver['identifier'], "access_code" => $password, "email" => $saver['email'], "ip" => getIPAddress(), "refurl" => getenv("HTTP_REFERER"), 'saved_thisstep' => 0, "status" => "S", "saved_date" => date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust));
     if ($connect->AutoExecute("{$dbprefix}saved_control", $scdata, 'INSERT')) {
         $scid = $connect->Insert_ID("{$dbprefix}saved_control", "scid");
         $dataentryoutput .= "<font class='successtitle'>" . $clang->gT("Your survey responses have been saved successfully.  You will be sent a confirmation e-mail. Please make sure to save your password, since we will not be able to retrieve it for you.") . "</font><br />\n";
         $tkquery = "SELECT * FROM " . db_table_name("tokens_{$surveyid}");
         if ($tkresult = $connect->Execute($tkquery)) {
             $tokendata = array("firstname" => $saver['identifier'], "lastname" => $saver['identifier'], "email" => $saver['email'], "token" => sRandomChars(15), "language" => $saver['language'], "sent" => date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust), "completed" => "N");
             $connect->AutoExecute(db_table_name("tokens_" . $surveyid), $tokendata, 'INSERT');
             $dataentryoutput .= "<font class='successtitle'>" . $clang->gT("A token entry for the saved survey has been created too.") . "</font><br />\n";
         }
         if ($saver['email']) {
             //Send email
             if (validate_email($saver['email']) && !returnglobal('redo')) {
                 $subject = $clang->gT("Saved Survey Details");
                 $message = $clang->gT("Thank you for saving your survey in progress.  The following details can be used to return to this survey and continue where you left off.  Please keep this e-mail for your reference - we cannot retrieve the password for you.");
                 $message .= "\n\n" . $thissurvey['name'] . "\n\n";
Ejemplo n.º 9
0
function do_shortfreetext($ia)
{
    global $thissurvey;
    $sGoogleMapsAPIKey = trim(Yii::app()->getConfig("googleMapsAPIKey"));
    if ($sGoogleMapsAPIKey != '') {
        $sGoogleMapsAPIKey = '&key=' . $sGoogleMapsAPIKey;
    }
    $extraclass = "";
    $aQuestionAttributes = getQuestionAttributeValues($ia[0]);
    if ($aQuestionAttributes['numbers_only'] == 1) {
        $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
        $sSeparator = $sSeparator['separator'];
        $extraclass .= " numberonly";
        $checkconditionFunction = "fixnum_checkconditions";
    } else {
        $checkconditionFunction = "checkconditions";
    }
    if (intval(trim($aQuestionAttributes['maximum_chars'])) > 0) {
        // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea
        $maximum_chars = intval(trim($aQuestionAttributes['maximum_chars']));
        $maxlength = "maxlength='{$maximum_chars}' ";
        $extraclass .= " maxchars maxchars-" . $maximum_chars;
    } else {
        $maxlength = "";
    }
    if (trim($aQuestionAttributes['text_input_width']) != '') {
        $tiwidth = $aQuestionAttributes['text_input_width'];
        $extraclass .= " inputwidth-" . trim($aQuestionAttributes['text_input_width']);
    } else {
        $tiwidth = 50;
    }
    if (trim($aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $prefix = $aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
        $extraclass .= " withprefix";
    } else {
        $prefix = '';
    }
    if (trim($aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $suffix = $aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
        $extraclass .= " withsuffix";
    } else {
        $suffix = '';
    }
    if ($thissurvey['nokeyboard'] == 'Y') {
        includeKeypad();
        $kpclass = "text-keypad";
        $extraclass .= " inputkeypad";
    } else {
        $kpclass = "";
    }
    if (trim($aQuestionAttributes['display_rows']) != '') {
        //question attribute "display_rows" is set -> we need a textarea to be able to show several rows
        $drows = $aQuestionAttributes['display_rows'];
        //if a textarea should be displayed we make it equal width to the long text question
        //this looks nicer and more continuous
        if ($tiwidth == 50) {
            $tiwidth = 40;
        }
        //NEW: textarea instead of input=text field
        // --> START NEW FEATURE - SAVE
        $answer = "<p class='question answer-item text-item {$extraclass}'><label for='answer{$ia[1]}' class='hide label'>" . gT('Your answer') . "</label>" . '<textarea class="textarea ' . $kpclass . '" name="' . $ia[1] . '" id="answer' . $ia[1] . '" ' . 'rows="' . $drows . '" cols="' . $tiwidth . '" ' . $maxlength . ' onkeyup="' . $checkconditionFunction . '(this.value, this.name, this.type);">';
        // --> END NEW FEATURE - SAVE
        if ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]) {
            $dispVal = str_replace("\\", "", $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]);
            if ($aQuestionAttributes['numbers_only'] == 1) {
                $dispVal = str_replace('.', $sSeparator, $dispVal);
            }
            $answer .= $dispVal;
        }
        $answer .= "</textarea></p>\n";
    } elseif ((int) $aQuestionAttributes['location_mapservice'] == 1) {
        $mapservice = $aQuestionAttributes['location_mapservice'];
        $currentLocation = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]];
        $currentLatLong = null;
        $floatLat = 0;
        $floatLng = 0;
        // Get the latitude/longtitude for the point that needs to be displayed by default
        if (strlen($currentLocation) > 2) {
            $currentLatLong = explode(';', $currentLocation);
            $currentLatLong = array($currentLatLong[0], $currentLatLong[1]);
        } else {
            if ((int) $aQuestionAttributes['location_nodefaultfromip'] == 0) {
                $currentLatLong = getLatLongFromIp(getIPAddress());
            }
            if (!isset($currentLatLong) || $currentLatLong == false) {
                $floatLat = 0;
                $floatLng = 0;
                $LatLong = explode(" ", trim($aQuestionAttributes['location_defaultcoordinates']));
                if (isset($LatLong[0]) && isset($LatLong[1])) {
                    $floatLat = $LatLong[0];
                    $floatLng = $LatLong[1];
                }
                $currentLatLong = array($floatLat, $floatLng);
            }
        }
        // 2 - city; 3 - state; 4 - country; 5 - postal
        $strBuild = "";
        if ($aQuestionAttributes['location_city']) {
            $strBuild .= "2";
        }
        if ($aQuestionAttributes['location_state']) {
            $strBuild .= "3";
        }
        if ($aQuestionAttributes['location_country']) {
            $strBuild .= "4";
        }
        if ($aQuestionAttributes['location_postal']) {
            $strBuild .= "5";
        }
        $currentLocation = $currentLatLong[0] . " " . $currentLatLong[1];
        $answer = "\n        <script type=\"text/javascript\">\n        zoom['{$ia['1']}'] = {$aQuestionAttributes['location_mapzoom']};\n        </script>\n\n        <div class=\"question answer-item geoloc-item {$extraclass}\">\n        <input type=\"hidden\" name=\"{$ia['1']}\" id=\"answer{$ia['1']}\" value=\"{$_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]}\">\n\n        <input class=\"text location " . $kpclass . "\" type=\"text\" size=\"20\" name=\"{$ia['1']}_c\"\n        id=\"answer{$ia['1']}_c\" value=\"{$currentLocation}\"\n        onchange=\"{$checkconditionFunction}(this.value, this.name, this.type)\" />\n\n        <input type=\"hidden\" name=\"boycott_{$ia['1']}\" id=\"boycott_{$ia['1']}\"\n        value = \"{$strBuild}\" >\n\n        <input type=\"hidden\" name=\"mapservice_{$ia['1']}\" id=\"mapservice_{$ia['1']}\"\n        class=\"mapservice\" value = \"{$aQuestionAttributes['location_mapservice']}\" >\n        <div id=\"gmap_canvas_{$ia['1']}_c\" style=\"width: {$aQuestionAttributes['location_mapwidth']}px; height: {$aQuestionAttributes['location_mapheight']}px\"></div>\n        </div>";
        Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "map.js");
        if ($aQuestionAttributes['location_mapservice'] == 1 && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") {
            Yii::app()->getClientScript()->registerScriptFile("https://maps.googleapis.com/maps/api/js?sensor=false{$sGoogleMapsAPIKey}");
        } else {
            if ($aQuestionAttributes['location_mapservice'] == 1) {
                Yii::app()->getClientScript()->registerScriptFile("http://maps.googleapis.com/maps/api/js?sensor=false{$sGoogleMapsAPIKey}");
            } elseif ($aQuestionAttributes['location_mapservice'] == 2) {
                Yii::app()->getClientScript()->registerScriptFile("http://www.openlayers.org/api/OpenLayers.js");
            }
        }
        if (isset($aQuestionAttributes['hide_tip']) && $aQuestionAttributes['hide_tip'] == 0) {
            $answer .= "<div class=\"questionhelp\">" . gT('Drag and drop the pin to the desired location. You may also right click on the map to move the pin.') . '</div>';
            $question_text['help'] = gT('Drag and drop the pin to the desired location. You may also right click on the map to move the pin.');
        }
    } elseif ((int) $aQuestionAttributes['location_mapservice'] == 100) {
        $currentLocation = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]];
        $currentCenter = $currentLatLong = null;
        // Get the latitude/longtitude for the point that needs to be displayed by default
        if (strlen($currentLocation) > 2 && strpos($currentLocation, ";")) {
            $currentLatLong = explode(';', $currentLocation);
            $currentCenter = $currentLatLong = array($currentLatLong[0], $currentLatLong[1]);
        } elseif ((int) $aQuestionAttributes['location_nodefaultfromip'] == 0) {
            $currentCenter = $currentLatLong = getLatLongFromIp(getIPAddress());
        }
        // If it's not set : set the center to the default position, but don't set the marker
        if (!$currentLatLong) {
            $currentLatLong = array("", "");
            $currentCenter = explode(" ", trim($aQuestionAttributes['location_defaultcoordinates']));
            if (count($currentCenter) != 2) {
                $currentCenter = array("", "");
            }
        }
        // 2 - city; 3 - state; 4 - country; 5 - postal
        // TODO : move it to aThisMapScriptVar and use geoname reverse geocoding (http://www.geonames.org/export/reverse-geocoding.html)
        $strBuild = "";
        /*if ($aQuestionAttributes['location_city'])
              $strBuild .= "2";
          if ($aQuestionAttributes['location_state'])
              $strBuild .= "3";
          if ($aQuestionAttributes['location_country'])
              $strBuild .= "4";
          if ($aQuestionAttributes['location_postal'])
              $strBuild .= "5";*/
        $aGlobalMapScriptVar = array('geonameUser' => getGlobalSetting('GeoNamesUsername'), 'geonameLang' => Yii::app()->language);
        $aThisMapScriptVar = array('zoomLevel' => $aQuestionAttributes['location_mapzoom'], 'latitude' => $currentCenter[0], 'longitude' => $currentCenter[1]);
        App()->getClientScript()->registerPackage('leaflet');
        Yii::app()->getClientScript()->registerScript('sGlobalMapScriptVar', "LSmap=" . ls_json_encode($aGlobalMapScriptVar) . ";\nLSmaps= new Array();", CClientScript::POS_HEAD);
        Yii::app()->getClientScript()->registerScript('sThisMapScriptVar' . $ia[1], "LSmaps['{$ia[1]}']=" . ls_json_encode($aThisMapScriptVar), CClientScript::POS_HEAD);
        Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "map.js");
        Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . 'map.css');
        $answer = "\n        <div class=\"question answer-item geoloc-item {$extraclass}\">\n            <input type=\"hidden\"  name=\"{$ia['1']}\" id=\"answer{$ia['1']}\" value=\"{$_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]}\"><!-- No javascript need a way to answer -->\n            <input type=\"hidden\" class=\"location\" name=\"{$ia['1']}_c\" id=\"answer{$ia['1']}_c\" value=\"{$currentLatLong[0]} {$currentLatLong[1]}\" />\n\n            <ul class=\"coordinates-list\">\n                <li class=\"coordinate-item\">" . gt("Latitude:") . "<input class=\"coords text\" type=\"text\" name=\"{$ia['1']}_c1\" id=\"answer_lat{$ia['1']}_c\"  value=\"{$currentLatLong[0]}\" /></li>\n                <li class=\"coordinate-item\">" . gt("Longitude:") . "<input class=\"coords text\" type=\"text\" name=\"{$ia['1']}_c2\" id=\"answer_lng{$ia['1']}_c\" value=\"{$currentLatLong[1]}\" /></li>\n            </ul>\n\n            <input type=\"hidden\" name=\"boycott_{$ia['1']}\" id=\"boycott_{$ia['1']}\" value = \"{$strBuild}\" > \n            <input type=\"hidden\" name=\"mapservice_{$ia['1']}\" id=\"mapservice_{$ia['1']}\" class=\"mapservice\" value = \"{$aQuestionAttributes['location_mapservice']}\" >\n\n            <div>\n                <div class=\"geoname_restrict\">\n                    <input type=\"checkbox\" id=\"restrictToExtent_{$ia[1]}\"> <label for=\"restrictToExtent_{$ia[1]}\">" . gt("Restrict search place to map extent") . "</label>\n                </div>\n                <div class=\"geoname_search\" >\n                    <input id=\"searchbox_{$ia[1]}\" placeholder=\"" . gt("Search") . "\" width=\"15\">\n                </div>\n            </div>\n            <div id=\"map_{$ia[1]}\" style=\"width: 100%; height: {$aQuestionAttributes['location_mapheight']}px;\">\n        </div>\n        ";
        if (isset($aQuestionAttributes['hide_tip']) && $aQuestionAttributes['hide_tip'] == 0) {
            $answer .= "<div class=\"questionhelp\">" . gT('Click to set the location or drag and drop the pin. You may may also enter coordinates') . '</div>';
            $question_text['help'] = gT('Click to set the location or drag and drop the pin. You may may also enter coordinates');
        }
    } else {
        //no question attribute set, use common input text field
        $answer = "<p class=\"question answer-item text-item {$extraclass}\">\n" . "<label for='answer{$ia[1]}' class='hide label'>" . gT('Your answer') . "</label>" . "{$prefix}\t<input class=\"text {$kpclass}\" type=\"text\" size=\"{$tiwidth}\" name=\"{$ia['1']}\" id=\"answer{$ia['1']}\"";
        $dispVal = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]];
        if ($aQuestionAttributes['numbers_only'] == 1) {
            $dispVal = str_replace('.', $sSeparator, $dispVal);
        }
        $dispVal = htmlspecialchars($dispVal, ENT_QUOTES, 'UTF-8');
        $answer .= " value=\"{$dispVal}\"";
        $answer .= " {$maxlength} onkeyup=\"{$checkconditionFunction}(this.value, this.name, this.type)\"/>\n\t{$suffix}\n</p>\n";
    }
    if (trim($aQuestionAttributes['time_limit']) != '') {
        $answer .= return_timer_script($aQuestionAttributes, $ia, "answer" . $ia[1]);
    }
    $inputnames[] = $ia[1];
    return array($answer, $inputnames);
}
Ejemplo n.º 10
0
function do_shortfreetext($ia)
{
    global $thissurvey;
    $clang = Yii::app()->lang;
    $sGoogleMapsAPIKey = trim(Yii::app()->getConfig("googleMapsAPIKey"));
    if ($sGoogleMapsAPIKey != '') {
        $sGoogleMapsAPIKey = '&key=' . $sGoogleMapsAPIKey;
    }
    $extraclass = "";
    $aQuestionAttributes = getQuestionAttributeValues($ia[0], $ia[4]);
    if ($aQuestionAttributes['numbers_only'] == 1) {
        $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
        $sSeparator = $sSeparator['separator'];
        $extraclass .= " numberonly";
        $checkconditionFunction = "fixnum_checkconditions";
    } else {
        $checkconditionFunction = "checkconditions";
    }
    if (intval(trim($aQuestionAttributes['maximum_chars'])) > 0) {
        // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea
        $maximum_chars = intval(trim($aQuestionAttributes['maximum_chars']));
        $maxlength = "maxlength='{$maximum_chars}' ";
        $extraclass .= " maxchars maxchars-" . $maximum_chars;
    } else {
        $maxlength = "";
    }
    if (trim($aQuestionAttributes['text_input_width']) != '') {
        $tiwidth = $aQuestionAttributes['text_input_width'];
        $extraclass .= " inputwidth-" . trim($aQuestionAttributes['text_input_width']);
    } else {
        $tiwidth = 50;
    }
    if (trim($aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $prefix = $aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
        $extraclass .= " withprefix";
    } else {
        $prefix = '';
    }
    if (trim($aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $suffix = $aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
        $extraclass .= " withsuffix";
    } else {
        $suffix = '';
    }
    if ($thissurvey['nokeyboard'] == 'Y') {
        includeKeypad();
        $kpclass = "text-keypad";
        $extraclass .= " inputkeypad";
    } else {
        $kpclass = "";
    }
    if (trim($aQuestionAttributes['display_rows']) != '') {
        //question attribute "display_rows" is set -> we need a textarea to be able to show several rows
        $drows = $aQuestionAttributes['display_rows'];
        //if a textarea should be displayed we make it equal width to the long text question
        //this looks nicer and more continuous
        if ($tiwidth == 50) {
            $tiwidth = 40;
        }
        //NEW: textarea instead of input=text field
        // --> START NEW FEATURE - SAVE
        $answer = "<p class='question answer-item text-item {$extraclass}'><label for='answer{$ia[1]}' class='hide label'>{$clang->gT('Answer')}</label>" . '<textarea class="textarea ' . $kpclass . '" name="' . $ia[1] . '" id="answer' . $ia[1] . '" ' . 'rows="' . $drows . '" cols="' . $tiwidth . '" ' . $maxlength . ' onkeyup="' . $checkconditionFunction . '(this.value, this.name, this.type);">';
        // --> END NEW FEATURE - SAVE
        if ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]) {
            $dispVal = str_replace("\\", "", $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]);
            if ($aQuestionAttributes['numbers_only'] == 1) {
                $dispVal = str_replace('.', $sSeparator, $dispVal);
            }
            $answer .= $dispVal;
        }
        $answer .= "</textarea></p>\n";
    } elseif ((int) $aQuestionAttributes['location_mapservice'] != 0) {
        $mapservice = $aQuestionAttributes['location_mapservice'];
        $currentLocation = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]];
        $currentLatLong = null;
        $floatLat = 0;
        $floatLng = 0;
        // Get the latitude/longtitude for the point that needs to be displayed by default
        if (strlen($currentLocation) > 2) {
            $currentLatLong = explode(';', $currentLocation);
            $currentLatLong = array($currentLatLong[0], $currentLatLong[1]);
        } else {
            if ((int) $aQuestionAttributes['location_nodefaultfromip'] == 0) {
                $currentLatLong = getLatLongFromIp(getIPAddress());
            }
            if (!isset($currentLatLong) || $currentLatLong == false) {
                $floatLat = 0;
                $floatLng = 0;
                $LatLong = explode(" ", trim($aQuestionAttributes['location_defaultcoordinates']));
                if (isset($LatLong[0]) && isset($LatLong[1])) {
                    $floatLat = $LatLong[0];
                    $floatLng = $LatLong[1];
                }
                $currentLatLong = array($floatLat, $floatLng);
            }
        }
        // 2 - city; 3 - state; 4 - country; 5 - postal
        $strBuild = "";
        if ($aQuestionAttributes['location_city']) {
            $strBuild .= "2";
        }
        if ($aQuestionAttributes['location_state']) {
            $strBuild .= "3";
        }
        if ($aQuestionAttributes['location_country']) {
            $strBuild .= "4";
        }
        if ($aQuestionAttributes['location_postal']) {
            $strBuild .= "5";
        }
        $currentLocation = $currentLatLong[0] . " " . $currentLatLong[1];
        $answer = "\n        <script type=\"text/javascript\">\n        zoom['{$ia['1']}'] = {$aQuestionAttributes['location_mapzoom']};\n        </script>\n        <div class=\"question answer-item geoloc-item {$extraclass}\">\n        <input type=\"hidden\" name=\"{$ia['1']}\" id=\"answer{$ia['1']}\" value=\"{$_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]}\">\n\n        <input class=\"text location " . $kpclass . "\" type=\"text\" size=\"20\" name=\"{$ia['1']}_c\"\n        id=\"answer{$ia['1']}_c\" value=\"{$currentLocation}\"\n        onchange=\"{$checkconditionFunction}(this.value, this.name, this.type)\" />\n\n        <input type=\"hidden\" name=\"boycott_{$ia['1']}\" id=\"boycott_{$ia['1']}\"\n        value = \"{$strBuild}\" >\n        <input type=\"hidden\" name=\"mapservice_{$ia['1']}\" id=\"mapservice_{$ia['1']}\"\n        class=\"mapservice\" value = \"{$aQuestionAttributes['location_mapservice']}\" >\n        <div id=\"gmap_canvas_{$ia['1']}_c\" style=\"width: {$aQuestionAttributes['location_mapwidth']}px; height: {$aQuestionAttributes['location_mapheight']}px\"></div>\n        </div>";
        Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "map.js");
        if ($aQuestionAttributes['location_mapservice'] == 1 && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") {
            Yii::app()->getClientScript()->registerScriptFile("https://maps.googleapis.com/maps/api/js?sensor=false{$sGoogleMapsAPIKey}");
        } else {
            if ($aQuestionAttributes['location_mapservice'] == 1) {
                Yii::app()->getClientScript()->registerScriptFile("http://maps.googleapis.com/maps/api/js?sensor=false{$sGoogleMapsAPIKey}");
            } elseif ($aQuestionAttributes['location_mapservice'] == 2) {
                Yii::app()->getClientScript()->registerScriptFile("http://www.openlayers.org/api/OpenLayers.js");
            }
        }
        if (isset($aQuestionAttributes['hide_tip']) && $aQuestionAttributes['hide_tip'] == 0) {
            $answer .= "<div class=\"questionhelp\">" . $clang->gT('Drag and drop the pin to the desired location. You may also right click on the map to move the pin.') . '</div>';
            $question_text['help'] = $clang->gT('Drag and drop the pin to the desired location. You may also right click on the map to move the pin.');
        }
    } else {
        //no question attribute set, use common input text field
        $answer = "<p class=\"question answer-item text-item {$extraclass}\">\n" . "<label for='answer{$ia[1]}' class='hide label'>{$clang->gT('Answer')}</label>" . "{$prefix}\t<input class=\"text {$kpclass}\" type=\"text\" size=\"{$tiwidth}\" name=\"{$ia['1']}\" id=\"answer{$ia['1']}\"";
        $dispVal = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]];
        if ($aQuestionAttributes['numbers_only'] == 1) {
            $dispVal = str_replace('.', $sSeparator, $dispVal);
        }
        $dispVal = htmlspecialchars($dispVal, ENT_QUOTES, 'UTF-8');
        $answer .= " value=\"{$dispVal}\"";
        $answer .= " {$maxlength} onkeyup=\"{$checkconditionFunction}(this.value, this.name, this.type)\"/>\n\t{$suffix}\n</p>\n";
    }
    if (trim($aQuestionAttributes['time_limit']) != '') {
        $answer .= return_timer_script($aQuestionAttributes, $ia, "answer" . $ia[1]);
    }
    $inputnames[] = $ia[1];
    return array($answer, $inputnames);
}
Ejemplo n.º 11
0
 /**
  * Write values to database.
  * @param <type> $updatedValues
  * @param <boolean> $finished - true if the survey needs to be finalized
  */
 private function _UpdateValuesInDatabase($updatedValues, $finished = false, $setSubmitDate = false)
 {
     // Update these values in the database
     global $connect;
     //  TODO - now that using $this->updatedValues, may be able to remove local copies of it (unless needed by other sub-systems)
     $updatedValues = $this->updatedValues;
     if (!$this->surveyOptions['deletenonvalues']) {
         $nonNullValues = array();
         foreach ($updatedValues as $key => $value) {
             if (!is_null($value)) {
                 if (isset($value['value']) && !is_null($value['value'])) {
                     $nonNullValues[$key] = $value;
                 }
             }
         }
         $updatedValues = $nonNullValues;
     }
     $message = '';
     if ($this->surveyOptions['datestamp'] == true && $this->surveyOptions['anonymized'] == true) {
         // On anonymous datestamped surveys, set the datestamp to 1-1-1980
         $datestamp = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980));
     } else {
         // Otherwise, use the real date/time, it will only be saved when the table holds a
         // datestamp field
         $datestamp = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
     }
     $_SESSION['datestamp'] = $datestamp;
     if ($this->surveyOptions['active'] && !isset($_SESSION['srid'])) {
         // Create initial insert row for this record
         $sdata = array("datestamp" => $datestamp, "ipaddr" => $this->surveyOptions['ipaddr'] ? getIPAddress() : '', "startlanguage" => $this->surveyOptions['startlanguage'], "token" => $this->surveyOptions['token'], "refurl" => $this->surveyOptions['refurl'] ? getenv("HTTP_REFERER") : NULL, "startdate" => $datestamp);
         //One of the strengths of ADOdb's AutoExecute() is that only valid field names for $table are updated
         if ($connect->AutoExecute($this->surveyOptions['tablename'], $sdata, 'INSERT')) {
             $srid = $connect->Insert_ID($this->surveyOptions['tablename'], "id");
             $_SESSION['srid'] = $srid;
         } else {
             $message .= $this->gT("Unable to insert record into survey table: ") . $connect->ErrorMsg() . "<br/>";
             $_SESSION['flashmessage'] = $message;
             echo $message;
         }
         //Insert Row for Timings, if needed
         if ($this->surveyOptions['savetimings']) {
             $tdata = array('id' => $srid, 'interviewtime' => 0);
             if ($connect->AutoExecute($this->surveyOptions['tablename_timings'], $tdata, 'INSERT')) {
                 $trid = $connect->Insert_ID($this->surveyOptions['tablename_timings'], "sid");
             } else {
                 $message .= $this->gT("Unable to insert record into timings table ") . $connect->ErrorMsg() . "<br/>";
                 $_SESSION['flashmessage'] = $message;
                 echo $message;
             }
         }
     }
     if (count($updatedValues) > 0 || $finished) {
         $query = 'UPDATE ' . $this->surveyOptions['tablename'] . " SET ";
         $setter = array();
         switch ($this->surveyMode) {
             case 'question':
                 $thisstep = $this->currentQuestionSeq;
                 break;
             case 'group':
                 $thisstep = $this->currentGroupSeq;
                 break;
             case 'survey':
                 $thisstep = 1;
                 break;
         }
         $setter[] = db_quote_id('lastpage') . "=" . db_quoteall($thisstep);
         if ($this->surveyOptions['datestamp'] && isset($_SESSION['datestamp'])) {
             $setter[] = db_quote_id('datestamp') . "=" . db_quoteall($_SESSION['datestamp']);
         }
         if ($this->surveyOptions['ipaddr']) {
             $setter[] = db_quote_id('ipaddr') . "=" . db_quoteall(getIPAddress());
         }
         foreach ($updatedValues as $key => $value) {
             if (!empty($key)) {
                 $val = is_null($value) ? NULL : $value['value'];
                 $type = is_null($value) ? NULL : $value['type'];
                 // Clean up the values to cope with database storage requirements
                 switch ($type) {
                     case 'D':
                         //DATE
                         if (trim($val) == '') {
                             $val = NULL;
                             // since some databases can't store blanks in date fields
                         }
                         // otherwise will already be in yyyy-mm-dd format after ProcessCurrentResponses()
                         break;
                     case '|':
                         //File upload
                         // This block can be removed once we require 5.3 or later
                         if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
                             $val = addslashes($val);
                         }
                         break;
                     case 'N':
                         //NUMERICAL QUESTION TYPE
                     //NUMERICAL QUESTION TYPE
                     case 'K':
                         //MULTIPLE NUMERICAL QUESTION
                         if (trim($val) == '') {
                             $val = NULL;
                             // since some databases can't store blanks in numerical inputs
                         }
                         break;
                     default:
                         break;
                 }
                 if (is_null($val)) {
                     $setter[] = db_quote_id($key) . "=NULL";
                 } else {
                     $setter[] = db_quote_id($key) . "=" . db_quoteall($val, true);
                 }
             }
         }
         $query .= implode(', ', $setter);
         $query .= " WHERE ID=";
         if (isset($_SESSION['srid']) && $this->surveyOptions['active']) {
             $query .= $_SESSION['srid'];
             if (!db_execute_assoc($query)) {
                 echo submitfailed($connect->ErrorMsg());
                 if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                     $message .= 'Error in SQL update: ' . $connect->ErrorMsg() . '<br/>';
                 }
             }
             // Save Timings if needed
             if ($this->surveyOptions['savetimings']) {
                 set_answer_time();
             }
             if ($finished) {
                 // Delete the save control record if successfully finalize the submission
                 $query = "DELETE FROM " . db_table_name("saved_control") . " where srid=" . $_SESSION['srid'] . ' and sid=' . $this->sid;
                 $connect->Execute($query);
                 // Checked
                 if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                     $message .= ';<br/>' . $query;
                 }
             } elseif ($this->surveyOptions['allowsave'] && isset($_SESSION['scid'])) {
                 $connect->Execute("UPDATE " . db_table_name("saved_control") . " SET saved_thisstep=" . db_quoteall($thisstep) . " where scid=" . $_SESSION['scid']);
                 // Checked
             }
             // Check quotas whenever results are saved
             $bQuotaMatched = false;
             $aQuotas = check_quota('return', $this->sid);
             if ($aQuotas !== false) {
                 if ($aQuotas != false) {
                     foreach ($aQuotas as $aQuota) {
                         if (isset($aQuota['status']) && $aQuota['status'] == 'matched') {
                             $bQuotaMatched = true;
                         }
                     }
                 }
             }
             if ($bQuotaMatched) {
                 check_quota('enforce', $this->sid);
                 // will create a page and quit.
             } else {
                 if ($finished) {
                     $sQuery = 'UPDATE ' . $this->surveyOptions['tablename'] . " SET " . db_quote_id('submitdate') . "=" . db_quoteall($datestamp) . " WHERE ID=" . $_SESSION['srid'];
                     $connect->Execute($sQuery);
                     // Checked
                 }
             }
         }
         if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
             $message .= $query;
         }
     }
     return $message;
 }
Ejemplo n.º 12
0
include 'info.php';
//MYSQL CONNECTION.
mysql_connect($serverAddress, $serverUsername, $serverPassword) or die(mysql_error());
mysql_select_db($serverDatabaseName) or die(mysql_error());
$portalUser = $_POST['login_user'];
//MYSQL QUERY.
$queryDataUser = mysql_query("SELECT * FROM userData WHERE portalUser = '******'");
//CHECK IF THE USER EXISTS.
if (mysql_num_rows($queryDataUser)) {
    $portalSalt = getInfo($portalUser, 'portalSalt');
    $portalHash = md5($_POST['login_password'] . md5($portalSalt));
    $queryDataPassword = mysql_query("SELECT * FROM userData WHERE portalUser = '******' AND portalPassword = '******'");
    //CHECK FOR A SUCCESSFUL LOGIN
    if (mysql_num_rows($queryDataPassword)) {
        //CREATE A SESSION.
        $_SESSION['userLoggedIn'] = true;
        $_SESSION['userUsername'] = getInfo($portalUser, 'portalUsername');
        $_SESSION['userEmail'] = getInfo($portalUser, 'portalEmail');
        $_SESSION['userName'] = getInfo($portalUser, 'portalName');
        $_SESSION['userRole'] = getInfo($portalUser, 'portalRole');
        //LOG NEW INFORMATION IN THE DATABASE.
        $currentUser = $_SESSION['userUsername'];
        $currentAddress = getIPAddress();
        mysql_query("UPDATE userData SET lastAddress = '{$currentAddress}' WHERE portalUser = '******'");
        echo "<script>window.open('../portal','_self')</script>";
    } else {
        echo "<script>window.open('../index?error=danger&title=Failed%20Login&message=The%20username%20or%20password%20entered%20was%20incorrect','_self')</script>";
    }
} else {
    echo "<script>window.open('../index?error=danger&title=Failed%20Login&message=The%20username%20or%20password%20entered%20was%20incorrect','_self')</script>";
}
Ejemplo n.º 13
0
 /**
  * Creates an attempt
  *
  * @access public
  * @return true
  */
 public function addAttempt()
 {
     $timestamp = date("Y-m-d H:i:s");
     $ip = substr(getIPAddress(), 0, 40);
     $row = $this->findByAttributes(array('ip' => $ip));
     if ($row !== null) {
         $row->number_attempts = $row->number_attempts + 1;
         $row->last_attempt = $timestamp;
         $row->save();
     } else {
         $record = new FailedLoginAttempt();
         $record->ip = $ip;
         $record->number_attempts = 1;
         $record->last_attempt = $timestamp;
         $record->save();
     }
     return true;
 }
Ejemplo n.º 14
0
                 //Checked
                 $loginsummary .= "<br />" . $clang->gT("Username") . ": {$fields['users_name']}<br />" . $clang->gT("Email") . ": {$emailaddr}<br />";
                 $loginsummary .= "<br />" . $clang->gT("An email with your login data was sent to you.");
                 $loginsummary .= "<br /><br /><a href='{$scriptname}'>" . $clang->gT("Continue") . "</a><br />&nbsp;\n";
             } else {
                 $tmp = str_replace("{NAME}", "<strong>" . $fields['users_name'] . "</strong>", $clang->gT("Email to {NAME} ({EMAIL}) failed."));
                 $loginsummary .= "<br />" . str_replace("{EMAIL}", $emailaddr, $tmp) . "<br />";
                 $loginsummary .= "<br /><br /><a href='{$scriptname}?action=forgotpassword'>" . $clang->gT("Continue") . "</a><br />&nbsp;\n";
             }
         }
     }
 } elseif ($action == "login" && $useWebserverAuth === false) {
     $loginsummary = '';
     if (isset($postuser) && isset($_POST['password'])) {
         include "database.php";
         $sIp = getIPAddress();
         $query = "SELECT * FROM " . db_table_name('failed_login_attempts') . " WHERE ip='{$sIp}';";
         $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
         $result = $connect->query($query);
         $bLoginAttempted = false;
         $bCannotLogin = false;
         $intNthAttempt = 0;
         if ($result !== false && $result->RecordCount() >= 1) {
             $bLoginAttempted = true;
             $field = $result->FetchRow();
             $intNthAttempt = $field['number_attempts'];
             if ($intNthAttempt >= $maxLoginAttempt) {
                 $bCannotLogin = true;
             }
             $iLastAttempt = strtotime($field['last_attempt']);
             if (time() > $iLastAttempt + $timeOutTime) {
Ejemplo n.º 15
0
function getIPv6Address($ip_bin)
{
    if (strlen($ip_bin) != 16) {
        throw new InvalidArgException('ip_bin', $ip_bin, "Invalid binary IP");
    }
    return getIPAddress($ip_bin);
}
Ejemplo n.º 16
0
<?php

session_start();
include 'config.php';
include 'info.php';
include 'mail.php';
//CHECK IF THE REGISTER DETAILS ARE CORRECT.
if ($_POST['register_password'] === $_POST['register_cpassword']) {
    //MYSQL CONNECTION.
    mysql_connect($serverAddress, $serverUsername, $serverPassword) or die(mysql_error());
    mysql_select_db($serverDatabaseName) or die(mysql_error());
    $portalUser = $_POST['register_username'];
    $portalEmail = $_POST['register_email'];
    $portalName = $_POST['register_fullname'];
    $portalSalt = md5(chr(mt_rand(ord('a'), ord('z'))) . substr(md5(time()), 1));
    $portalHash = md5($_POST['register_password'] . md5($portalSalt));
    $portalRegisterIP = getIPAddress();
    //MYSQL QUERY.
    $createUser = "******";
    //PERFORM THE FOLLOWING ON A SUCCESSFUL REGISTRATION.
    if (mysql_query($createUser)) {
        sendVerifyMessage($portalEmail, $portalUser, $portalName);
        echo "<script>window.open('../index?error=success&title=Registration%20Success&message=The%20registration%20was%20complete.%20Please%20login%20below','_self')</script>";
        //PERFORM THE FOLLOWING ON A FAILED REGISTRATION.
    } else {
        echo "<script>window.open('../index?error=danger&title=Failed%20Registration&message=The%20registration%20failed%20to%20complete,%20please%20try%20again%20later','_self')</script>";
    }
} else {
    echo "<script>window.open('../index?error=danger&title=Failed%20Registration&message=The%20passwords%20entered%20did%20not%20match','_self')</script>";
}
Ejemplo n.º 17
0
function amplifyAllocationList($alloc_list)
{
    $ret = array();
    $sorted = array();
    foreach ($alloc_list as $ip_bin => $alloc) {
        $sorted[$alloc['osif']][$ip_bin] = $alloc;
    }
    foreach (sortPortList($sorted) as $osif => $subarray) {
        foreach ($subarray as $ip_bin => $alloc) {
            $alloc['addrinfo'] = getIPAddress($ip_bin);
            $ret[$ip_bin] = $alloc;
        }
    }
    return $ret;
}
Ejemplo n.º 18
0
Archivo: api.php Proyecto: xtha/salt
     assertUIntArg("rack_id", TRUE);
     $rackData = spotEntity('rack', $_REQUEST['rack_id']);
     amplifyCell($rackData);
     sendAPIResponse($rackData);
     break;
     // get info for a single IP address
     //    UI equivalent: /index.php?page=ipaddress&hl_object_id=911&ip=10.200.1.66
     //    UI handler: renderIPAddress()
 // get info for a single IP address
 //    UI equivalent: /index.php?page=ipaddress&hl_object_id=911&ip=10.200.1.66
 //    UI handler: renderIPAddress()
 case 'get_ipaddress':
     require_once 'inc/init.php';
     assertStringArg("ip", TRUE);
     // basic IP address info
     $address = getIPAddress(ip_parse($_REQUEST['ip']));
     $address['network_id'] = getIPAddressNetworkId(ip_parse($_REQUEST['ip']));
     // TODO: add some / all of the following data
     // virtual services
     //  ! empty $address['vslist']
     //      foreach $address['vslist'] as $vs_id
     //         $blah = spotEntity ('ipv4vs', $vs_id)
     // RS pools
     // allocations
     // departing NAT rules
     // arriving NAT rules
     sendAPIResponse($address);
     break;
     // get one object
     //    UI equivalent: /index.php?page=object&object_id=909
     //    UI handler: renderObject()
Ejemplo n.º 19
0
function snmpgeneric_list($object_id)
{
    global $sg_create_noconnector_ports, $sg_known_sysObjectIDs, $sg_portoifoptions, $sg_ifType_ignore;
    if (isset($_POST['snmpconfig'])) {
        $snmpconfig = $_POST;
    } else {
        showError("Missing SNMP Config");
        return;
    }
    //	sg_var_dump_html($snmpconfig);
    echo '<body onload="document.getElementById(\'createbutton\').focus();">';
    addJS('function setchecked(classname) { var boxes = document.getElementsByClassName(classname);
				 var value = document.getElementById(classname).checked;
				 for(i=0;i<boxes.length;i++) {
					if(boxes[i].disabled == false)
						boxes[i].checked=value;
				 }
		};', TRUE);
    $object = spotEntity('object', $object_id);
    $object['attr'] = getAttrValues($object_id);
    $snmpdev = new mySNMP($snmpconfig['version'], $snmpconfig['host'], $snmpconfig['community']);
    if ($snmpconfig['version'] == "v3") {
        $snmpdev->setSecurity($snmpconfig['sec_level'], $snmpconfig['auth_protocol'], $snmpconfig['auth_passphrase'], $snmpconfig['priv_protocol'], $snmpconfig['priv_passphrase']);
    }
    $snmpdev->init();
    if ($snmpdev->getErrno()) {
        showError($snmpdev->getError());
        return;
    }
    /* SNMP connect successfull */
    showSuccess("SNMP " . $snmpconfig['version'] . " connect to {$snmpconfig['host']} successfull");
    echo '<form name=CreatePorts method=post action=' . $_SERVER['REQUEST_URI'] . '&module=redirect&op=create>';
    echo "<strong>System Informations</strong>";
    echo "<table>";
    //	echo "<tr><th>OID</th><th>Value</th></tr>";
    $systemoids = array('sysDescr', 'sysObjectID', 'sysUpTime', 'sysContact', 'sysName', 'sysLocation');
    foreach ($systemoids as $shortoid) {
        $value = $snmpdev->{$shortoid};
        if ($shortoid == 'sysUpTime') {
            /* in hundredths of a second */
            $secs = (int) ($value / 100);
            $days = (int) ($secs / (60 * 60 * 24));
            $secs -= $days * 60 * 60 * 24;
            $hours = (int) ($secs / (60 * 60));
            $secs -= $hours * 60 * 60;
            $mins = (int) ($secs / 60);
            $secs -= $mins * 60;
            $value = "{$value} ({$days} {$hours}:{$mins}:{$secs})";
        }
        echo "<tr><td title=\"" . $snmpdev->lastgetoid . "\" align=\"right\">{$shortoid}: </td><td>{$value}</td></tr>";
    }
    unset($shortoid);
    echo "</table>";
    /* sysObjectID Attributes and Ports */
    $sysObjectID['object'] =& $object;
    /* get sysObjectID */
    $sysObjectID['raw_value'] = $snmpdev->sysObjectID;
    //$sysObjectID['raw_value'] = 'NET-SNMP-MIB::netSnmpAgentOIDs.10';
    $sysObjectID['value'] = preg_replace('/^.*enterprises\\.([\\.[:digit:]]+)$/', '\\1', $sysObjectID['raw_value']);
    /* try snmptranslate to numeric */
    if (preg_match('/[^\\.0-9]+/', $sysObjectID['value'])) {
        $numeric_value = $snmpdev->translatetonumeric($sysObjectID['value']);
        if (!empty($numeric_value)) {
            showSuccess("sysObjectID: " . $sysObjectID['value'] . " translated to {$numeric_value}");
            $sysObjectID['value'] = preg_replace('/^.1.3.6.1.4.1.([\\.[:digit:]]+)$/', '\\1', $numeric_value);
        }
    }
    /* array_merge doesn't work with numeric keys !! */
    $sysObjectID['attr'] = array();
    $sysObjectID['port'] = array();
    $sysobjid = $sysObjectID['value'];
    $count = 1;
    while ($count) {
        if (isset($sg_known_sysObjectIDs[$sysobjid])) {
            $sysObjectID = $sysObjectID + $sg_known_sysObjectIDs[$sysobjid];
            if (isset($sg_known_sysObjectIDs[$sysobjid]['attr'])) {
                $sysObjectID['attr'] = $sysObjectID['attr'] + $sg_known_sysObjectIDs[$sysobjid]['attr'];
            }
            if (isset($sg_known_sysObjectIDs[$sysobjid]['port'])) {
                $sysObjectID['port'] = $sysObjectID['port'] + $sg_known_sysObjectIDs[$sysobjid]['port'];
            }
            if (isset($sg_known_sysObjectIDs[$sysobjid]['text'])) {
                showSuccess("found sysObjectID ({$sysobjid}) " . $sg_known_sysObjectIDs[$sysobjid]['text']);
            }
        }
        $sysobjid = preg_replace('/\\.[[:digit:]]+$/', '', $sysobjid, 1, $count);
        /* add default sysobjectid */
        if ($count == 0 && $sysobjid != 'default') {
            $sysobjid = 'default';
            $count = 1;
        }
    }
    $sysObjectID['vendor_number'] = $sysobjid;
    /* device pf */
    if (isset($sysObjectID['pf'])) {
        foreach ($sysObjectID['pf'] as $function) {
            if (function_exists($function)) {
                /* call device pf */
                $function($snmpdev, $sysObjectID, NULL);
            } else {
                showWarning("Missing processor function " . $function . " for device {$sysobjid}");
            }
        }
    }
    /* sort attributes maintain numeric keys */
    ksort($sysObjectID['attr']);
    /* DEBUG */
    //sg_var_dump_html($sysObjectID['attr'], "Before processing");
    /* needs PHP >= 5 foreach call by reference */
    /* php 5.1.6 doesn't seem to work */
    //foreach($sysObjectID['attr'] as $attr_id => &$attr)
    foreach ($sysObjectID['attr'] as $attr_id => $value) {
        $attr =& $sysObjectID['attr'][$attr_id];
        if (isset($object['attr'][$attr_id])) {
            if (array_key_exists('key', $object['attr'][$attr_id])) {
                $attr['key'] = $object['attr'][$attr_id]['key'];
            }
            switch (TRUE) {
                case isset($attr['pf']):
                    if (function_exists($attr['pf'])) {
                        $attr['pf']($snmpdev, $sysObjectID, $attr_id);
                    } else {
                        showWarning("Missing processor function " . $attr['pf'] . " for attribute {$attr_id}");
                    }
                    break;
                case isset($attr['oid']):
                    $attrvalue = $snmpdev->get($attr['oid']);
                    if (isset($attr['regex'])) {
                        $regex = $attr['regex'];
                        if (isset($attr['replacement'])) {
                            $replacement = $attr['replacement'];
                            $attrvalue = preg_replace($regex, $replacement, $attrvalue);
                        } else {
                            if (!preg_match($regex, $attrvalue)) {
                                if (!isset($attr['uncheck'])) {
                                    $attr['uncheck'] = "regex doesn't match";
                                }
                            } else {
                                unset($attr['uncheck']);
                            }
                        }
                    }
                    $attr['value'] = $attrvalue;
                    break;
                case isset($attr['value']):
                    break;
                default:
                    showError("Error handling attribute id: {$attr_id}");
            }
        } else {
            showWarning("Object has no attribute id: {$attr_id}");
            unset($sysObjectID['attr'][$attr_id]);
        }
    }
    unset($attr_id);
    /* sort again in case there where attribs added ,maintain numeric keys */
    ksort($sysObjectID['attr']);
    /* print attributes */
    echo '<br>Attributes<br><table>';
    echo '<tr><th><input type="checkbox" id="attribute" checked="checked" onclick="setchecked(this.id)"></td>';
    echo '<th>Name</th><th>Current Value</th><th>new value</th></tr>';
    /* DEBUG */
    //sg_var_dump_html($sysObjectID['attr'], "After processing");
    foreach ($sysObjectID['attr'] as $attr_id => &$attr) {
        $attr['id'] = $attr_id;
        if (isset($object['attr'][$attr_id]) && isset($attr['value'])) {
            if ($attr['value'] == $object['attr'][$attr_id]['value']) {
                $attr['uncheck'] = 'Current = new value';
            }
            if (isset($attr['key']) && isset($object['attr'][$attr_id]['key'])) {
                if ($attr['key'] == $object['attr'][$attr_id]['key']) {
                    $attr['uncheck'] = 'Current = new key';
                }
            }
            $value = $attr['value'];
            $val_key = isset($object['attr'][$attr_id]['key']) ? ' (' . $object['attr'][$attr_id]['key'] . ')' : '';
            $comment = '';
            if (isset($attr['comment'])) {
                if (!empty($attr['comment'])) {
                    $comment = $attr['comment'];
                }
            }
            if (isset($attr['uncheck'])) {
                $checked = '';
                $comment .= ', ' . $attr['uncheck'];
            } else {
                $checked = ' checked="checked"';
            }
            $updateattrcheckbox = '<b style="background-color:#00ff00">' . '<input style="background-color:#00ff00" class="attribute" type="checkbox" name="updateattr[' . $attr_id . ']" value="' . $value . '"' . $checked . '></b>';
            $comment = trim($comment, ', ');
            echo "<tr><td>{$updateattrcheckbox}</td><td title=\"id: {$attr_id}\">" . $object['attr'][$attr_id]['name'] . '</td><td style="background-color:#d8d8d8">' . $object['attr'][$attr_id]['value'] . $val_key . '</td><td>' . $value . '</td>' . '<td style="color:#888888">' . $comment . '</td></tr>';
        }
    }
    unset($attr_id);
    echo '</table>';
    $object['breed'] = sg_detectDeviceBreedByObject($sysObjectID);
    if (!empty($object['breed'])) {
        echo "Found Breed: " . $object['breed'] . "<br>";
    }
    /* ports */
    /* get ports */
    amplifyCell($object);
    /* set array key to lowercase port name */
    foreach ($object['ports'] as $key => $values) {
        $object['ports'][strtolower(shortenIfName($values['name'], $object['breed']))] = $values;
        unset($object['ports'][$key]);
    }
    $newporttypeoptions = getNewPortTypeOptions();
    //	sg_var_dump_html($sysObjectID['port']);
    if (!empty($sysObjectID['port'])) {
        echo '<br>Vendor / Device specific ports<br>';
        echo '<table><tr><th><input type="checkbox" id="moreport" checked="checked" onclick="setchecked(this.id)"></th><th>ifName</th><th>porttypeid</th></tr>';
        foreach ($sysObjectID['port'] as $name => $port) {
            if (array_key_exists(strtolower($name), $object['ports'])) {
                $disableport = TRUE;
            } else {
                $disableport = FALSE;
            }
            $comment = '';
            if (isset($port['comment'])) {
                if (!empty($port['comment'])) {
                    $comment = $port['comment'];
                }
            }
            if (isset($port['uncheck'])) {
                $checked = '';
                $comment .= ', ' . $port['uncheck'];
            } else {
                $checked = ' checked="checked"';
            }
            $portcreatecheckbox = '<b style="background-color:' . ($disableport ? '#ff0000' : '#00ff00') . '"><input style="background-color:' . ($disableport ? '#ff0000' : '#00ff00') . '" class="moreport" type="checkbox" name="portcreate[' . $name . ']" value="' . $name . '"' . ($disableport ? ' disabled="disbaled"' : $checked) . '></b>';
            $formfield = '<input type="hidden" name="ifName[' . $name . ']" value="' . $name . '">';
            echo "<tr>{$formfield}<td>{$portcreatecheckbox}</td><td>{$name}</td>";
            if (isset($port['disabled'])) {
                $disabledselect = array('disabled' => "disabled");
            } else {
                $disabledselect = array();
            }
            foreach ($port as $key => $value) {
                if ($key == 'uncheck' || $key == 'comment') {
                    continue;
                }
                /* TODO iif_name */
                if ($key == 'porttypeid') {
                    $displayvalue = getNiftySelect($newporttypeoptions, array('name' => "porttypeid[{$name}]") + $disabledselect, $value);
                } else {
                    $displayvalue = $value;
                }
                $formfield = '<input type="hidden" name="' . $key . '[' . $name . ']" value="' . $value . '">';
                echo "{$formfield}<td>{$displayvalue}</td>";
            }
            $comment = trim($comment, ', ');
            echo "<td style=\"color:#888888\">{$comment}</td></tr>";
        }
        unset($name);
        unset($port);
        echo '</table>';
    }
    /* snmp ports */
    $ifsnmp = new ifSNMP($snmpdev);
    // needed for shortenIfName()
    $ifsnmp->object_breed = $object['breed'];
    /* ip spaces */
    $ipspace = NULL;
    foreach ($ifsnmp->ipaddress as $ifindex => $ipaddresses) {
        foreach ($ipaddresses as $ipaddr => $value) {
            $addrtype = $value['addrtype'];
            $netaddr = $value['net'];
            $maskbits = $value['maskbits'];
            $netid = NULL;
            $linklocal = FALSE;
            //echo "<br> - DEBUG: ipspace $ipaddr - $netaddr - $addrtype - $maskbits<br>";
            /* check for ip space */
            switch ($addrtype) {
                case 'ipv4':
                case 'ipv4z':
                    if ($maskbits == 32) {
                        $netid = 'host';
                    } else {
                        $netid = getIPv4AddressNetworkId(ip_parse($ipaddr));
                    }
                    break;
                case 'ipv6':
                    if (ip_checkparse($ipaddr) === false) {
                        /* format ipaddr for ip6_parse */
                        $ipaddr = preg_replace('/((..):(..))/', '\\2\\3', $ipaddr);
                        $ipaddr = preg_replace('/%.*$/', '', $ipaddr);
                    }
                    if (ip_checkparse($ipaddr) === false) {
                        continue 2;
                    }
                    // 2 because of switch
                    $ip6_bin = ip6_parse($ipaddr);
                    $ip6_addr = ip_format($ip6_bin);
                    $netid = getIPv6AddressNetworkId($ip6_bin);
                    $node = constructIPRange($ip6_bin, $maskbits);
                    $netaddr = $node['ip'];
                    $linklocal = substr($ip6_addr, 0, 5) == "fe80:";
                    //echo "<br> - DEBUG: ipspace $ipaddr - $addrtype - $maskbits - $netaddr - >$linklocal<<br>";
                    break;
                case 'ipv6z':
                    /* link local */
                    $netid = 'ignore';
                    break;
                default:
            }
            if (empty($netid) && $netaddr != '::1' && $netaddr != '127.0.0.1' && $netaddr != '127.0.0.0' && $netaddr != '0.0.0.0' && !$linklocal) {
                $netaddr .= "/{$maskbits}";
                $ipspace[$netaddr] = array('addrtype' => $addrtype, 'checked' => $maskbits > 0 ? true : false);
            }
        }
        unset($ipaddr);
        unset($value);
        unset($addrtype);
    }
    unset($ifindex);
    unset($ipaddresses);
    /* print ip spaces table */
    if (!empty($ipspace)) {
        echo '<br><br>Create IP Spaces';
        echo '<table><tr><th><input type="checkbox" id="ipspace" onclick="setchecked(this.id)" checked=\\"checked\\"></th>';
        echo '<th>Type</th><th>prefix</th><th>name</th><th width=150 title="reserve network and router addresses">reserve network / router addresses</th></tr>';
        $i = 1;
        foreach ($ipspace as $prefix => $ipspace) {
            $netcreatecheckbox = '<b style="background-color:#00ff00">' . '<input class="ipspace" style="background-color:#00ff00" type="checkbox" name="netcreate[' . $i . ']" value="' . $ipspace['addrtype'] . '"' . ($ipspace['checked'] ? ' checked=\\"checked\\"' : '') . '></b>';
            $netprefixfield = '<input type="text" size=50 name="netprefix[' . $i . ']" value="' . $prefix . '">';
            $netnamefield = '<input type="text" name="netname[' . $i . ']">';
            $netreservecheckbox = '<input type="checkbox" name="netreserve[' . $i . ']" checked="checked">';
            echo "<tr><td>{$netcreatecheckbox}</td><td style=\"color:#888888\">{$ipspace['addrtype']}</td><td>{$netprefixfield}</td><td>{$netnamefield}</td><td>{$netreservecheckbox}</td></tr>";
            $i++;
        }
        unset($prefix);
        unset($addrtype);
        unset($i);
        echo '</table>';
    }
    echo "<br><br>ifNumber: " . $ifsnmp->ifNumber . "<br>indexcount: " . $ifsnmp->indexcount . "<br><table><tbody valign=\"top\">";
    $portcompat = getPortInterfaceCompat();
    $ipnets = array();
    $ifsnmp->printifInfoTableHeader("<th>add ip</th><th>add port</th><th>upd label</th><th title=\"update mac\">upd mac</th><td>upd port type</th><th>porttypeid</th><th>comment</th></tr>");
    echo '<tr><td colspan="11"></td>
		<td><input type="checkbox" id="ipaddr" onclick="setchecked(this.id);" checked="checked">IPv4<br>
		<input type="checkbox" id="ipv6addr" onclick="setchecked(this.id);" checked="checked">IPv6</td>
		<td><input type="checkbox" id="ports" onclick="setchecked(this.id)"></td>
		<td><input type="checkbox" id="label" onclick="setchecked(this.id);" checked="checked"></td>
		<td><input type="checkbox" id="mac" onclick="setchecked(this.id);" checked="checked"></td>
		<td><input type="checkbox" id="porttype" onclick="setchecked(this.id);"></td></tr>';
    foreach ($ifsnmp as $if) {
        $createport = TRUE;
        $disableport = FALSE;
        $ignoreport = FALSE;
        $port_info = NULL;
        $updatelabel = false;
        $updateporttype = false;
        $updatemaccheckbox = '';
        $hrefs = array();
        $comment = "";
        if (trim($ifsnmp->ifName($if)) == '') {
            $comment .= "no ifName";
            $createport = FALSE;
        } else {
            if (array_key_exists($ifsnmp->ifName($if), $object['ports'])) {
                $port_info =& $object['ports'][$ifsnmp->ifName($if)];
                $comment .= "Name exists";
                /* ifalias change */
                if ($port_info['label'] != $ifsnmp->ifAlias($if)) {
                    $updatelabel = true;
                }
                $createport = FALSE;
                $disableport = TRUE;
            }
        }
        if ($ifsnmp->ifPhysAddress($if) != '') {
            $ifPhysAddress = $ifsnmp->ifPhysAddress($if);
            $l2port = sg_checkL2Address($ifPhysAddress);
            if (!empty($l2port)) {
                $l2object_id = key($l2port);
                $porthref = makeHref(array('page' => 'object', 'tab' => 'ports', 'object_id' => $l2object_id, 'hl_port_id' => $l2port[$l2object_id]));
                $comment .= ", L2Address exists";
                $hrefs['ifPhysAddress'] = $porthref;
                $createport = FALSE;
                //	$disableport = TRUE;
                $updatemaccheckbox = '';
            }
            $disablemac = true;
            if ($disableport) {
                if ($port_info !== NULL) {
                    if (str_replace(':', '', $port_info['l2address']) != $ifPhysAddress) {
                        $disablemac = false;
                    } else {
                        $disablemac = true;
                    }
                }
            } else {
                /* port create always updates mac */
                $updatemaccheckbox = '<b style="background-color:#00ff00">' . '<input style="background-color:' . '#00ff00" type="checkbox"' . ' checked="checked"' . ' disabled=\\"disabled\\"></b>';
            }
            if (!$disablemac) {
                $updatemaccheckbox = '<b style="background-color:' . ($disablemac ? '#ff0000' : '#00ff00') . '">' . '<input class="mac" style="background-color:' . ($disablemac ? '#ff0000' : '#00ff00') . '" type="checkbox" name="updatemac[' . $if . ']" value="' . $object['ports'][$ifsnmp->ifName($if)]['id'] . '" checked="checked"' . ($disablemac ? ' disabled=\\"disabled\\"' : '') . '></b>';
            }
        }
        $porttypeid = guessRToif_id($ifsnmp->ifType($if), $ifsnmp->ifDescr($if));
        if (in_array($ifsnmp->ifType($if), $sg_ifType_ignore)) {
            $comment .= ", ignore if type";
            $createport = FALSE;
            $ignoreport = TRUE;
        } else {
            if ($port_info) {
                $ptid = $port_info['iif_id'] . "-" . $port_info['oif_id'];
                if ($porttypeid != $ptid) {
                    $comment .= ", Update Type {$ptid} -> {$porttypeid}";
                    $updateporttype = true;
                }
            }
        }
        /* ignore ports without an Connector */
        if (!$sg_create_noconnector_ports && $ifsnmp->ifConnectorPresent($if) == 2) {
            $comment .= ", no Connector";
            $createport = FALSE;
        }
        /* Allocate IPs ipv4 and ipv6 */
        $ipaddresses = $ifsnmp->ipaddress($if);
        if (!empty($ipaddresses)) {
            $ipaddrcell = '<table>';
            foreach ($ipaddresses as $ipaddr => $value) {
                $createipaddr = FALSE;
                $disableipaddr = FALSE;
                $ipaddrhref = '';
                $linklocal = FALSE;
                $addrtype = $value['addrtype'];
                $maskbits = $value['maskbits'];
                $bcast = $value['bcast'];
                //echo "<br> - DEBUG: ip $ipaddr - $addrtype - $maskbits - $bcast<br>";
                switch ($addrtype) {
                    case 'ipv4z':
                    case 'ipv4':
                        if ($maskbits == 32) {
                            $bcast = "host";
                        }
                        $inputname = 'ip';
                        break;
                    case 'ipv6z':
                        $disableipaddr = TRUE;
                    case 'ipv6':
                        $inputname = 'ipv6';
                        if (ip_checkparse($ipaddr) === false) {
                            /* format ipaddr for ip6_parse */
                            $ipaddr = preg_replace('/((..):(..))/', '\\2\\3', $ipaddr);
                            $ipaddr = preg_replace('/%.*$/', '', $ipaddr);
                        }
                        if (ip_checkparse($ipaddr) === false) {
                            continue 2;
                        }
                        // 2 because of switch
                        /* ip_parse throws exception on parse errors */
                        $ip6_bin = ip_parse($ipaddr);
                        $ipaddr = ip_format($ip6_bin);
                        $node = constructIPRange($ip6_bin, $maskbits);
                        $linklocal = $node['ip'] == 'fe80::';
                        $createipaddr = FALSE;
                        break;
                }
                //switch
                $address = getIPAddress(ip_parse($ipaddr));
                /* only if ip not already allocated */
                if (empty($address['allocs'])) {
                    if (!$ignoreport) {
                        $createipaddr = TRUE;
                    }
                } else {
                    $disableipaddr = TRUE;
                    $ipobject_id = $address['allocs'][0]['object_id'];
                    $ipaddrhref = makeHref(array('page' => 'object', 'object_id' => $ipobject_id, 'hl_ipv4_addr' => $ipaddr));
                }
                /* reserved addresses */
                if ($address['reserved'] == 'yes') {
                    $comment .= ', ' . $address['ip'] . ' reserved ' . $address['name'];
                    $createipaddr = FALSE;
                    //	$disableipaddr = TRUE;
                }
                if ($ipaddr == '127.0.0.1' || $ipaddr == '0.0.0.0' || $ipaddr == '::1' || $ipaddr == '::' || $linklocal) {
                    $createipaddr = FALSE;
                    $disableipaddr = TRUE;
                }
                if ($ipaddr === $bcast) {
                    $comment .= ", {$ipaddr} broadcast";
                    $createipaddr = FALSE;
                    $disableipaddr = TRUE;
                }
                if (!$disableipaddr) {
                    $ipaddrcheckbox = '<b style="background-color:' . ($disableipaddr ? '#ff0000' : '#00ff00') . '"><input class="' . $inputname . 'addr" style="background-color:' . ($disableipaddr ? '#ff0000' : '#00ff00') . '" type="checkbox" name="' . $inputname . 'addrcreate[' . $ipaddr . ']" value="' . $if . '"' . ($disableipaddr ? ' disabled="disabled"' : '') . ($createipaddr ? ' checked="checked"' : '') . '></b>';
                } else {
                    $ipaddrcheckbox = '';
                }
                $ipaddrcell .= "<tr><td>{$ipaddrcheckbox}</td>";
                if (!empty($ipaddrhref)) {
                    $ipaddrcell .= "<td><a href={$ipaddrhref}>{$ipaddr}/{$maskbits}</a></td></tr>";
                } else {
                    $ipaddrcell .= "<td>{$ipaddr}/{$maskbits}</td></tr>";
                }
            }
            // foreach
            unset($ipaddr);
            unset($value);
            $ipaddrcell .= '</table>';
            // if(!empty($ipaddresses))
        } else {
            $ipaddrcreatecheckbox = '';
            $ipaddrcell = '';
        }
        /* checkboxes for add port and add ip */
        /* FireFox needs <b style=..>, IE and Opera work with <td style=..> */
        if (!$disableport) {
            $portcreatecheckbox = '<b style="background-color:' . ($disableport ? '#ff0000' : '#00ff00') . '"><input class="ports" style="background-color:' . ($disableport ? '#ff0000' : '#00ff00') . '" type="checkbox" name="portcreate[' . $if . ']" value="' . $if . '"' . ($disableport ? ' disabled="disbaled"' : '') . ($createport ? ' checked="checked"' : '') . '></b>';
        } else {
            $portcreatecheckbox = '';
        }
        /* port type id */
        /* add port type to newporttypeoptions if missing */
        if (strpos(serialize($newporttypeoptions), $porttypeid) === FALSE) {
            $portids = explode('-', $porttypeid);
            $oif_name = $sg_portoifoptions[$portids[1]];
            $newporttypeoptions['auto'] = array($porttypeid => "*{$oif_name}");
        }
        $selectoptions = array('name' => "porttypeid[{$if}]");
        if ($disableport && !$updateporttype) {
            $selectoptions['disabled'] = "disabled";
        }
        $updateporttypecheckbox = "";
        if ($updateporttype) {
            $updateporttypecheckbox = '<b style="background-color:#00ff00;">' . '<input class="porttype" style="background-color:#00ff00;" type="checkbox" name="updateporttype[' . $if . ']" value="' . $port_info['id'] . '"></b>';
        }
        $porttypeidselect = getNiftySelect($newporttypeoptions, $selectoptions, $porttypeid);
        $updatelabelcheckbox = "";
        if ($updatelabel) {
            $updatelabelcheckbox = '<b style="background-color:#00ff00;">' . '<input class="label" style="background-color:#00ff00;" type="checkbox" name="updatelabel[' . $if . ']" value="' . $port_info['id'] . ($updatelabel ? '" checked="checked"' : '') . '></b>';
        }
        $comment = trim($comment, ', ');
        $ifsnmp->printifInfoTableRow($if, "<td>{$ipaddrcell}</td><td>{$portcreatecheckbox}</td><td>{$updatelabelcheckbox}</td><td>{$updatemaccheckbox}</td><td>{$updateporttypecheckbox}</td><td>{$porttypeidselect}</td><td nowrap=\"nowrap\">{$comment}</td>", $hrefs);
    }
    unset($if);
    /* preserve snmpconfig */
    foreach ($_POST as $key => $value) {
        echo '<input type=hidden name=' . $key . ' value=' . $value . ' />';
    }
    unset($key);
    unset($value);
    echo '<tr><td colspan=15 align="right"><p><input id="createbutton" type=submit value="Create Ports and IPs" onclick="return confirm(\'Create selected items?\')"></p></td></tr></tbody></table></form>';
}
Ejemplo n.º 20
0
function dynamic_title_decoder($path_position)
{
    global $sic, $page_by_realm;
    static $net_id;
    try {
        switch ($path_position) {
            case 'index':
                return array('name' => '/' . getConfigVar('enterprise'), 'params' => array());
            case 'chapter':
                $chapter_no = assertUIntArg('chapter_no');
                $chapters = getChapterList();
                $chapter_name = isset($chapters[$chapter_no]) ? $chapters[$chapter_no]['name'] : 'N/A';
                return array('name' => "Chapter '{$chapter_name}'", 'params' => array('chapter_no' => $chapter_no));
            case 'user':
                $userinfo = spotEntity('user', assertUIntArg('user_id'));
                return array('name' => "Local user '" . $userinfo['user_name'] . "'", 'params' => array('user_id' => $userinfo['user_id']));
            case 'ipv4rspool':
                $pool_info = spotEntity('ipv4rspool', assertUIntArg('pool_id'));
                return array('name' => !strlen($pool_info['name']) ? 'ANONYMOUS' : $pool_info['name'], 'params' => array('pool_id' => $pool_info['id']));
            case 'ipv4vs':
                $vs_info = spotEntity('ipv4vs', assertUIntArg('vs_id'));
                return array('name' => $vs_info['dname'], 'params' => array('vs_id' => $vs_info['id']));
            case 'ipvs':
                $vs_info = spotEntity('ipvs', assertUIntArg('vs_id'));
                return array('name' => $vs_info['name'], 'params' => array('vs_id' => $vs_info['id']));
            case 'object':
                $object = spotEntity('object', assertUIntArg('object_id'));
                return array('name' => $object['dname'], 'params' => array('object_id' => $object['id']));
            case 'location':
                $location = spotEntity('location', assertUIntArg('location_id'));
                return array('name' => $location['name'], 'params' => array('location_id' => $location['id']));
            case 'row':
                global $pageno;
                switch ($pageno) {
                    case 'rack':
                        $rack = spotEntity('rack', assertUIntArg('rack_id'));
                        return array('name' => $rack['row_name'], 'params' => array('row_id' => $rack['row_id'], 'location_id' => $rack['location_id']));
                    case 'row':
                        $row_info = getRowInfo(assertUIntArg('row_id'));
                        return array('name' => $row_info['name'], 'params' => array('row_id' => $row_info['id'], 'location_id' => $row_info['location_id']));
                    default:
                        break;
                }
            case 'rack':
                $rack_info = spotEntity('rack', assertUIntArg('rack_id'));
                return array('name' => $rack_info['name'], 'params' => array('rack_id' => $rack_info['id']));
            case 'search':
                if (isset($_REQUEST['q'])) {
                    return array('name' => "search results for '{$_REQUEST['q']}'", 'params' => array('q' => $_REQUEST['q']));
                } else {
                    return array('name' => 'search results', 'params' => array());
                }
            case 'file':
                $file = spotEntity('file', assertUIntArg('file_id'));
                return array('name' => niftyString($file['name'], 30, FALSE), 'params' => array('file_id' => $_REQUEST['file_id']));
            case 'ipaddress':
                $address = getIPAddress(ip_parse($_REQUEST['ip']));
                return array('name' => niftyString($address['ip'] . ($address['name'] != '' ? ' (' . $address['name'] . ')' : ''), 50, FALSE), 'params' => array('ip' => $address['ip']));
            case 'ipv4net':
            case 'ipv6net':
                global $pageno;
                switch ($pageno) {
                    case 'ipaddress':
                        $net = spotNetworkByIP(ip_parse($_REQUEST['ip']));
                        $ret = array('name' => $net['ip'] . '/' . $net['mask'], 'params' => array('id' => $net['id'], 'page' => $net['realm'], 'hl_ip' => $_REQUEST['ip']));
                        return $ret;
                    default:
                        $net = spotEntity($path_position, assertUIntArg('id'));
                        return array('name' => $net['ip'] . '/' . $net['mask'], 'params' => array('id' => $net['id']));
                }
                break;
            case 'ipv4space':
            case 'ipv6space':
                global $pageno;
                switch ($pageno) {
                    case 'ipaddress':
                        $net_id = getIPAddressNetworkId(ip_parse($_REQUEST['ip']));
                        break;
                    case 'ipv4net':
                    case 'ipv6net':
                        $net_id = $_REQUEST['id'];
                        break;
                    default:
                        $net_id = NULL;
                }
                $params = array();
                if (isset($net_id)) {
                    $params = array('eid' => $net_id, 'hl_net' => 1, 'clear-cf' => '');
                }
                unset($net_id);
                $ip_ver = preg_replace('/[^\\d]*/', '', $path_position);
                return array('name' => "IPv{$ip_ver} space", 'params' => $params);
            case 'vlandomain':
                global $pageno;
                switch ($pageno) {
                    case 'vlandomain':
                        $vdom_id = $_REQUEST['vdom_id'];
                        break;
                    case 'vlan':
                        list($vdom_id, $dummy) = decodeVLANCK($_REQUEST['vlan_ck']);
                        break;
                    default:
                        break;
                }
                $vdlist = getVLANDomainOptions();
                if (!array_key_exists($vdom_id, $vdlist)) {
                    throw new EntityNotFoundException('VLAN domain', $vdom_id);
                }
                return array('name' => niftyString("domain '" . $vdlist[$vdom_id] . "'", 20, FALSE), 'params' => array('vdom_id' => $vdom_id));
            case 'vlan':
                return array('name' => formatVLANAsPlainText(getVLANInfo($sic['vlan_ck'])), 'params' => array('vlan_ck' => $sic['vlan_ck']));
            case 'vst':
                $vst = spotEntity('vst', $sic['vst_id']);
                return array('name' => niftyString("template '" . $vst['description'] . "'", 50, FALSE), 'params' => array('vst_id' => $sic['vst_id']));
            case 'dqueue':
                global $dqtitle;
                return array('name' => 'queue "' . $dqtitle[$sic['dqcode']] . '"', 'params' => array('qcode' => $sic['dqcode']));
            default:
                break;
        }
        // default behaviour is throwing an exception
        throw new RackTablesError('dynamic_title decoding error', RackTablesError::INTERNAL);
    } catch (RackTablesError $e) {
        return array('name' => __FUNCTION__ . '() failure', 'params' => array());
    }
}
Ejemplo n.º 21
0
function updateIPCommentAJAX()
{
    global $sic;
    assertStringArg('text', TRUE);
    $ip_bin = assertIPArg('id');
    $addr = getIPAddress($ip_bin);
    $net = spotNetworkByIP($ip_bin);
    if (isset($net)) {
        fixContext($net);
    }
    assertPermission('ipaddress', 'properties', 'editAddress');
    updateAddress($ip_bin, $addr['name'], $addr['reserved'], $sic['text']);
    echo 'OK';
}
Ejemplo n.º 22
0
function addIPAllocation()
{
    setFuncMessages(__FUNCTION__, array('OK' => 48, 'ERR1' => 170));
    $ip_bin = assertIPArg('ip');
    assertUIntArg('object_id');
    assertStringArg('bond_name', TRUE);
    genericAssertion('bond_type', 'enum/alloc_type');
    // check if address is alread allocated
    $address = getIPAddress($ip_bin);
    if (!empty($address['allocs']) && ($address['allocs'][0]['type'] != 'shared' || $_REQUEST['bond_type'] != 'shared')) {
        showWarning("IP " . ip_format($ip_bin) . " already in use by " . $address['allocs'][0]['object_name'] . " - " . $address['allocs'][0]['name']);
    }
    if (getConfigVar('IPV4_JAYWALK') != 'yes' and NULL === getIPAddressNetworkId($ip_bin)) {
        showFuncMessage(__FUNCTION__, 'ERR1', array(ip_format($ip_bin)));
        return;
    }
    if ($address['reserved'] && strlen($address['name'])) {
        showWarning("IP " . ip_format($ip_bin) . " reservation \"" . $address['name'] . "\" is removed");
        //TODO ask to take reserved IP or not !
    }
    bindIPToObject($ip_bin, $_REQUEST['object_id'], $_REQUEST['bond_name'], $_REQUEST['bond_type']);
    showFuncMessage(__FUNCTION__, 'OK');
    return buildRedirectURL(NULL, NULL, array('hl_ip' => ip_format($ip_bin)));
}