Example #1
0
 public function actionView($id)
 {
     $model = new People();
     $people = $model->findByPk($id);
     $data = Yii::app()->db->createCommand()->select('*')->from('People')->where('family_id=:id', array('id' => (int) $people['family_id']))->order('lvl ASC')->queryAll();
     $this->render('view', array('peoples' => $data));
 }
 public function testDelete()
 {
     $this->_mock = new Mock_Database($this, array(array('many', "SELECT *\nFROM people\nWHERE `id` IN (?, ?)", array(1, 2), null, array('return' => array(array('id' => '1', 'passport_id' => 3), array('id' => '2', 'passport_id' => 4)))), array('execute', "DELETE FROM people\nWHERE `id` IN (?, ?)", array(1, 2)), array('many', "SELECT *\nFROM passports\nWHERE `id` IN (?, ?)", array(3, 4), null, array('return' => array(array('id' => '3'), array('id' => '4')))), array('execute', "DELETE FROM passports\nWHERE `id` IN (?, ?)", array(3, 4))), array('debug' => false));
     \Snowfire\Database\Model::database($this->_mock);
     $people_model = new People();
     $passports_model = new Passports();
     $people_model->delete(array('id' => array(1, 2)), array('passports' => $passports_model));
 }
Example #3
0
 /**
  * Store a newly created resource in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function store(Request $request)
 {
     //
     $name = $request->input("name");
     $age = $request->input("age");
     $people = new People();
     $people->name = $name;
     $people->age = $age;
     $people->save();
     return "name={{$name}}, age={{$age}}";
 }
 public function registerAction()
 {
     echo "RegStart";
     $user = new People();
     //Store and check for errors
     $success = $user->save($this->request->getPost(), array('name', 'email'));
     if ($success) {
         echo "Thanks for registering!";
     } else {
         echo "Sorry, the following problems were generated: ";
         foreach ($user->getMessages() as $message) {
             echo $message->getMessage(), "<br/>";
         }
     }
     $this->view->disable();
 }
 public function actionBirthdays()
 {
     $model = new People();
     if (isset($_POST['period'])) {
         header("Content-Type: application/vnd.ms-excel; charset=utf-8");
         header("Content-Disposition: inline; filename=\"birthdays-report.xls\"");
         $dt = $_POST['People']['dob'];
         $dt = date('Y-m-d', CDateTimeParser::parse($dt, Yii::app()->locale->getDateFormat('short')));
         $period = $_POST['period'];
         $nxt_bday = "MAKEDATE(YEAR('{$dt}')+IF(DAYOFYEAR(t.dob)<DAYOFYEAR('{$dt}'),1,0),DAYOFYEAR(t.dob))";
         $cond = "{$nxt_bday} BETWEEN '{$dt}' AND '{$dt}' + INTERVAL 1 {$period} ORDER BY {$nxt_bday}";
         Yii::trace("R.birthdays dt={$dt}, period={$period}, cond={$cond}", 'application.controllers.ReportController');
         $crit = new CDbCriteria();
         $crit->addCondition($cond);
         $dataProvider = new CActiveDataProvider('People', array('criteria' => $crit));
         $dataProvider->pagination = false;
         $fields = array('id', 'fname', 'lname', 'dob', 'mobile');
         $labels = $model->attributeLabels();
         $fval = array();
         foreach ($fields as $field) {
             array_push($fval, $labels[$field]);
         }
         echo implode("\t", $fval) . "\n";
         foreach ($dataProvider->data as $data) {
             $fval = array();
             foreach ($fields as $field) {
                 array_push($fval, $data->{$field});
             }
             echo implode("\t", $fval) . "\n";
         }
         Yii::app()->end();
         return;
     }
     $this->render('birthdays', array('model' => $model));
 }
Example #6
0
 /**
  * Singleton Pattern
  *
  * Auto Create Object Instance.
  *
  */
 public static function getInstance()
 {
     if (null === self::$_objInstance) {
         self::$_objInstance = new People();
     }
     return self::$_objInstance;
 }
Example #7
0
 function relativeList($id = NULL, $list_args = NULL)
 {
     if (is_null($list_args)) {
         $list_args = array('name' => array('heading' => '名称', 'cell' => '{name}'), 'phone' => array('heading' => '电话'), 'email' => array('heading' => '电邮'), 'relation' => array('heading' => '关系'));
     }
     return parent::relativeList($id, $list_args);
 }
 public function configure()
 {
     $this->useFields(array('is_physical', 'family_name', 'activity_date_to', 'activity_date_from'));
     $this->addPagerItems();
     $this->widgetSchema['family_name'] = new sfWidgetFormInput();
     $this->widgetSchema['is_physical'] = new sfWidgetFormInputHidden();
     $this->setDefault('is_physical', true);
     $yearsKeyVal = range(intval(sfConfig::get('dw_yearRangeMin')), intval(sfConfig::get('dw_yearRangeMax')));
     $minDate = new FuzzyDateTime(strval(min($yearsKeyVal) . '/01/01'));
     $maxDate = new FuzzyDateTime(strval(max($yearsKeyVal) . '/12/31'));
     $dateLowerBound = new FuzzyDateTime(sfConfig::get('dw_dateLowerBound'));
     $dateUpperBound = new FuzzyDateTime(sfConfig::get('dw_dateUpperBound'));
     $maxDate->setStart(false);
     $this->widgetSchema['activity_date_from'] = new widgetFormJQueryFuzzyDate($this->getDateItemOptions(), array('class' => 'from_date'));
     $this->widgetSchema['activity_date_to'] = new widgetFormJQueryFuzzyDate($this->getDateItemOptions(), array('class' => 'to_date'));
     $this->validatorSchema['activity_date_from'] = new fuzzyDateValidator(array('required' => false, 'from_date' => true, 'min' => $minDate, 'max' => $maxDate, 'empty_value' => $dateLowerBound), array('invalid' => 'Date provided is not valid'));
     $this->validatorSchema['activity_date_to'] = new fuzzyDateValidator(array('required' => false, 'from_date' => false, 'min' => $minDate, 'max' => $maxDate, 'empty_value' => $dateUpperBound), array('invalid' => 'Date provided is not valid'));
     $people_types = array('' => '');
     $types = People::getTypes();
     foreach ($types as $flag => $name) {
         $people_types[strval($flag)] = $name;
     }
     $this->widgetSchema['people_type'] = new sfWidgetFormChoice(array('choices' => $people_types));
     $this->widgetSchema['people_type']->setLabel('Role');
     $this->validatorSchema['people_type'] = new sfValidatorChoice(array('required' => false, 'choices' => array_keys($people_types)));
     $this->validatorSchema->setPostValidator(new sfValidatorSchemaCompare('activity_date_from', '<=', 'activity_date_to', array('throw_global_error' => true), array('invalid' => 'The to date cannot be above the "end" date.')));
 }
Example #9
0
 function index()
 {
     $this->config->set_user_item('search/in_same_project_with', $this->user->id, false);
     if (!$this->config->user_item('search/labels')) {
         $this->config->set_user_item('search/labels', array('成交客户'));
     }
     parent::index();
 }
 public function actionProfile()
 {
     $fams = Families::model()->findAll();
     $ppl = People::model()->findAll();
     $baptised = People::model()->getBaptised();
     $confirmed = People::model()->getConfirmed();
     $married = People::model()->getMarried();
     $this->render('profile', array('families' => count($fams), 'members' => count($ppl), 'baptised' => count($baptised), 'confirmed' => count($confirmed), 'married' => count($married)));
 }
 /**
  * @test
  */
 public function shouldBeAbleToUseLimitQuery()
 {
     // given
     LudoDB::enableSqlLogging();
     $this->createPeople();
     $people = new People(4330);
     $values = $people->getValues(0, 10);
     // then
     $this->assertEquals(10, count($values));
 }
Example #12
0
 function __construct()
 {
     $this->permission = array('signup' => true, 'login' => true, 'logout' => array(), 'submit' => true, 'setfields' => true, 'profile' => array(), 'match' => true);
     parent::__construct();
     $this->people = $this->user;
     if ($this->company->ucenter) {
         require APPPATH . 'third_party/ucenter_client/config.php';
         require APPPATH . 'third_party/ucenter_client/client.php';
     }
 }
 /** The constructor
  * @access public
  * @param array $options
  * @return void
  */
 public function __construct(array $options = null)
 {
     $curators = new People();
     $assigned = $curators->getValuers();
     ZendX_JQuery::enableForm($this);
     parent::__construct($options);
     $this->setName('provisionalvaluations');
     $valuerID = new Zend_Form_Element_Select('valuerID');
     $valuerID->setLabel('Valuation provided by: ')->setRequired(true)->addFilters(array('StripTags', 'StringTrim'))->setAttrib('class', 'input-xxlarge selectpicker show-menu-arrow')->addValidator('StringLength', false, array(1, 25))->addValidator('InArray', false, array(array_keys($assigned)))->addMultiOptions($assigned);
     $value = new Zend_Form_Element_Text('value');
     $value->setLabel('Estimated market value: ')->setRequired(true)->addFilters(array('StripTags', 'StringTrim'))->addValidator('Float');
     $comments = new Pas_Form_Element_CKEditor('comments');
     $comments->setLabel('Valuation comments: ')->setRequired(false)->setAttrib('rows', 10)->setAttrib('cols', 40)->setAttrib('Height', 400)->setAttrib('ToolbarSet', 'Finds')->addFilters(array('StringTrim', 'BasicHtml', 'EmptyParagraph', 'WordChars'));
     $dateOfValuation = new ZendX_JQuery_Form_Element_DatePicker('dateOfValuation');
     $dateOfValuation->setLabel('Valuation provided on: ')->setRequired(true)->setJQueryParam('dateFormat', 'yy-mm-dd')->addFilters(array('StripTags', 'StringTrim'))->setAttrib('size', 20);
     $submit = new Zend_Form_Element_Submit('submit');
     $this->addElements(array($valuerID, $value, $dateOfValuation, $comments, $submit));
     $this->addDisplayGroup(array('valuerID', 'value', 'dateOfValuation', 'comments'), 'details');
     $this->addDisplayGroup(array('submit'), 'buttons');
     parent::init();
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate($id)
 {
     $model = new MembershipCertificate();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['MembershipCertificate'])) {
         $model->attributes = $_POST['MembershipCertificate'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $rec = People::model()->findByPk($id);
     $model->cert_dt = Yii::app()->dateFormatter->formatDateTime(time(), 'short', null);
     $this->render('create', array('model' => $model, 'member' => $rec));
 }
Example #15
0
 function __construct()
 {
     parent::__construct();
     $this->load->model('contact_model', 'contact');
     $this->people = $this->contact;
     $this->load->view_path['edit'] = 'client/edit';
     $this->form_validation_rules['people'] = array(array('field' => 'profiles[来源类型]', 'label' => '客户来源类型', 'rules' => 'required'), array('field' => 'people[staff]', 'label' => '来源律师', 'rules' => 'required'));
     if ($this->user->isLogged('service')) {
         $this->list_args += array('uid' => array('heading' => '添加人', 'parser' => array('function' => function ($uid) {
             return $this->user->fetch($uid, 'name');
         }, 'args' => array('uid'))), 'time_insert' => array('heading' => '添加时间', 'parser' => array('function' => function ($time_insert) {
             return date('Y-m-d', $time_insert);
         }, 'args' => array('time_insert'))));
         $this->search_items = array_merge($this->search_items, array('time_insert/from', 'time_insert/to', 'uid'));
     }
 }
Example #16
0
 /**
  * 设置、取消用户的实验室成员身份
  * @param unknown $id
  */
 public function actionTogglePeople($id)
 {
     $user = $this->loadModel($id);
     $people = $user->people;
     if ($people) {
         if ($people->delete()) {
             Yii::app()->user->setFlash('success', '已将用户移除实验室成员!');
         }
     } else {
         $people = new People();
         $people->name = $user->name;
         $people->userId = $user->id;
         $people->email = $user->email;
         if ($people->save()) {
             Yii::app()->user->setFlash('success', '已将用户设为实验室成员!');
         }
     }
     $this->redirect(array('admin'));
 }
Example #17
0
 public function actionWedding($id)
 {
     $model = new People();
     $people = $model->findByPk($id);
     if (isset($_POST['People'])) {
         if (isset($_POST['People']['wedding']) && $_POST['People']['wedding'] == null) {
             $model->wedding = 0;
         } else {
             $model->wedding = $_POST['People']['wedding'];
         }
         if ($id != $model->wedding) {
             $model->isCanWedding($people['family_id']) && $model->wedding($id, $model->wedding, $people['family_id'], $people['lvl']) && $this->redirect(Yii::app()->createUrl('people'));
         } else {
             $model->addPeopleError('Человек не может быть сам себе парой');
         }
     }
     $people['wedding'] > 0 && $model->addPeopleError('У этого человека уже есть пара');
     $this->render('wedding', array('model' => $model, 'wedding' => $people['wedding'], 'fam_id' => $people['family_id']));
 }
Example #18
0
function upgrade()
{
    global $version;
    global $config;
    global $results;
    global $dbh;
    global $errormsg;
    if ($version == "") {
        // something borked re-apply all database updates and pray for forgiveness
        $version = "1.2";
    }
    if ($version == "1.2") {
        // Do 1.2 to 1.3 Update
        $results[] = applyupdate("db-1.2-to-1.3.sql");
        $version = "1.3";
    }
    if ($version == "1.3") {
        // Do 1.3 to 1.4 Update
        // Clean the configuration table of any duplicate values that might have been added.
        $config->rebuild();
        $results[] = applyupdate("db-1.3-to-1.4.sql");
        $version = "1.4";
    }
    if ($version == "1.4") {
        // Do 1.4 to 1.5 Update
        // A few of the database changes require some tests to ensure that they will be able to apply.
        // Both of these need to return 0 results before we continue or the database schema update will not complete.
        $conflicts = 0;
        $sql = "SELECT PDUID, CONCAT(PDUID,'-',PDUPosition) AS KEY1, COUNT(PDUID) AS Count  FROM fac_PowerConnection GROUP BY KEY1 HAVING (COUNT(KEY1)>1) ORDER BY PDUID ASC;";
        $sth = $dbh->prepare($sql);
        $sth->execute();
        $conflicts += $sth->rowCount() > 0 ? 1 : 0;
        $sql = "SELECT DeviceID, CONCAT(DeviceID,'-',DeviceConnNumber) AS KEY2, COUNT(DeviceID) AS Count FROM fac_PowerConnection GROUP BY KEY2 HAVING (COUNT(KEY2)>1) ORDER BY DeviceID ASC;";
        $sth = $dbh->prepare($sql);
        $sth->execute();
        $conflicts += $sth->rowCount() > 0 ? 1 : 0;
        $sql = "SELECT SwitchDeviceID, CONCAT(SwitchDeviceID,'-',SwitchPortNumber) AS KEY1, COUNT(SwitchDeviceID) AS Count FROM fac_SwitchConnection GROUP BY KEY1 HAVING (COUNT(KEY1)>1) ORDER BY SwitchDeviceID ASC;";
        $sth = $dbh->prepare($sql);
        $sth->execute();
        $conflicts += $sth->rowCount() > 0 ? 1 : 0;
        $sql = "SELECT SwitchDeviceID, SwitchPortNumber, EndpointDeviceID, EndpointPort, CONCAT(EndpointDeviceID,'-',EndpointPort) AS KEY2, COUNT(EndpointDeviceID) AS Count FROM fac_SwitchConnection GROUP BY KEY2 HAVING (COUNT(KEY2)>1) ORDER BY EndpointDeviceID ASC;";
        $sth = $dbh->prepare($sql);
        $sth->execute();
        $conflicts += $sth->rowCount() > 0 ? 1 : 0;
        require_once "facilities.inc.php";
        if ($conflicts != 0) {
            header('Location: ' . redirect("conflicts.php"));
            exit;
        }
        $config->rebuild();
        $results[] = applyupdate("db-1.4-to-1.5.sql");
        $version = "1.5";
    }
    if ($version == "1.5") {
        // Do the 1.5 to 2.0 Update
        // Get a list of all Manufacturers that are duplicated
        $sql = "SELECT ManufacturerID,Name FROM fac_Manufacturer GROUP BY Name HAVING COUNT(*)>1;";
        foreach ($dbh->query($sql) as $row) {
            // Set all devices with that Manufacturer to the ID of just one
            $sql = "UPDATE fac_DeviceTemplate SET ManufacturerID={$row["ManufacturerID"]} WHERE ManufacturerID IN (SELECT ManufacturerID FROM fac_Manufacturer WHERE Name=\"{$row["Name"]}\");";
            $dbh->query($sql);
            // Delete all the duplicates other than the one you set everything to
            $sql = "DELETE FROM fac_Manufacturer WHERE Name=\"{$row["Name"]}\" and ManufacturerID!={$row["ManufacturerID"]};";
            $dbh->query($sql);
        }
        // Repeat for Templates
        $sql = "SELECT TemplateID,ManufacturerID,Model FROM fac_DeviceTemplate GROUP BY ManufacturerID,Model HAVING COUNT(*)>1;";
        foreach ($dbh->query($sql) as $row) {
            $sql = "UPDATE fac_Device SET TemplateID={$row["TemplateID"]} WHERE TemplateID IN (SELECT TemplateID FROM fac_DeviceTemplate WHERE ManufacturerID={$row["ManufacturerID"]} AND Model=\"{$row["Model"]}\");";
            $dbh->query($sql);
            $sql = "DELETE FROM fac_DeviceTemplate WHERE ManufacturerID={$row["ManufacturerID"]} AND TemplateID!={$row["TemplateID"]};";
            $dbh->query($sql);
        }
        // And finally, Departments
        $sql = "SELECT DeptID, Name FROM fac_Department GROUP BY Name HAVING COUNT(*)>1;";
        foreach ($dbh->query($sql) as $row) {
            $sql = "UPDATE fac_Device SET Owner={$row["DeptID"]} WHERE Owner IN (SELECT DeptID FROM fac_Department WHERE Name=\"{$row["Name"]}\");";
            $dbh->query($sql);
            // Yes, I know, this may create duplicates
            $sql = "UPDATE fac_DeptContacts SET DeptID={$row["DeptID"]} WHERE DeptID IN (SELECT DeptID FROM fac_Department WHERE Name=\"{$row["Name"]}\");";
            $dbh->query($sql);
            $sql = "DELETE FROM fac_Department WHERE Name=\"{$row["Name"]}\" AND DeptID!={$row["DeptID"]};";
            $dbh->query($sql);
        }
        // So delete the potential duplicate contact links created in the last step
        $sql = "SELECT DeptID,ContactID FROM fac_DeptContacts GROUP BY DeptID,ContactID HAVING COUNT(*)>1;";
        foreach ($dbh->query($sql) as $row) {
            $sql = "DELETE FROM fac_DeptContacts WHERE DeptID={$row["DeptID"]} AND ContactID={$row["ContactID"]};";
            $dbh->query($sql);
            $sql = "INSERT INTO fac_DeptContacts VALUES ({$row["DeptID"]},{$row["ContactID"]});";
            $dbh->query($sql);
        }
        /* 
         /  Clean up multiple key issues.
         /
         /	1. Identify Multiple Keys
         /	2. Remove them
         /	3. Recreate keys based on structure in create.sql
         /
        */
        $array = array();
        $sql = "SHOW INDEXES FROM fac_PowerConnection;";
        foreach ($dbh->query($sql) as $row) {
            $array[$row["Key_name"]] = 1;
        }
        foreach ($array as $key => $garbage) {
            $sql = "ALTER TABLE fac_PowerConnection DROP INDEX {$key};";
            $dbh->query($sql);
        }
        $sql = "ALTER TABLE fac_PowerConnection ADD UNIQUE KEY PDUID (PDUID,PDUPosition);";
        $dbh->query($sql);
        $sql = "ALTER TABLE fac_PowerConnection ADD UNIQUE KEY DeviceID (DeviceID,DeviceConnNumber);";
        $dbh->query($sql);
        // Just removing keys from fac_CabinetAudit
        $array = array();
        $sql = "SHOW INDEXES FROM fac_CabinetAudit;";
        foreach ($dbh->query($sql) as $row) {
            $array[$row["Key_name"]] = 1;
        }
        foreach ($array as $key => $garbage) {
            $sql = "ALTER TABLE fac_CabinetAudit DROP INDEX {$key};";
            $dbh->query($sql);
        }
        $array = array();
        $sql = "SHOW INDEXES FROM fac_Department;";
        foreach ($dbh->query($sql) as $row) {
            $array[$row["Key_name"]] = 1;
        }
        foreach ($array as $key => $garbage) {
            $sql = "ALTER TABLE fac_Department DROP INDEX {$key};";
            $dbh->query($sql);
        }
        $sql = "ALTER TABLE fac_Department ADD PRIMARY KEY (DeptID);";
        $dbh->query($sql);
        $sql = "ALTER TABLE fac_Department ADD UNIQUE KEY Name (Name);";
        $dbh->query($sql);
        $config->rebuild();
        $results[] = applyupdate("db-1.5-to-2.0.sql");
        $version = "2.0";
    }
    if ($version == "2.0") {
        $sql = "select InputAmperage from fac_PowerDistribution limit 1";
        // See if the field exists - some people have manually added the missing one already, so we can't add what's already there
        if (!$dbh->query($sql)) {
            //		if(mysql_errno($facDB)==1054){
            $sql = "ALTER TABLE fac_PowerDistribution ADD COLUMN InputAmperage INT(11) NOT NULL AFTER PanelPole";
            $dbh->query($sql);
        }
        $sql = 'UPDATE fac_Config SET Value="2.0.1" WHERE Parameter="Version"';
        $dbh->query($sql);
        $version = "2.0.1";
    }
    if ($version == "2.0.1") {
        // Get a list of all Manufacturers that are duplicated
        $sql = "SELECT ManufacturerID,Name FROM fac_Manufacturer GROUP BY Name HAVING COUNT(*)>1;";
        foreach ($dbh->query($sql) as $row) {
            // Set all devices with that Manufacturer to the ID of just one
            $sql = "UPDATE fac_DeviceTemplate SET ManufacturerID={$row["ManufacturerID"]} WHERE ManufacturerID IN (SELECT ManufacturerID FROM fac_Manufacturer WHERE Name=\"{$row["Name"]}\");";
            $dbh->query($sql);
            // Delete all the duplicates other than the one you set everything to
            $sql = "DELETE FROM fac_Manufacturer WHERE Name=\"{$row["Name"]}\" and ManufacturerID!={$row["ManufacturerID"]};";
            $dbh->query($sql);
        }
        // Repeat for Templates
        $sql = "SELECT TemplateID,ManufacturerID,Model FROM fac_DeviceTemplate GROUP BY ManufacturerID,Model HAVING COUNT(*)>1;";
        foreach ($dbh->query($sql) as $row) {
            $sql = "UPDATE fac_Device SET TemplateID={$row["TemplateID"]} WHERE TemplateID IN (SELECT TemplateID FROM fac_DeviceTemplate WHERE ManufacturerID={$row["ManufacturerID"]} AND Model=\"{$row["Model"]}\");";
            $dbh->query($sql);
            $sql = "DELETE FROM fac_DeviceTemplate WHERE ManufacturerID={$row["ManufacturerID"]} AND TemplateID!={$row["TemplateID"]};";
            $dbh->query($sql);
        }
        // Clean up multiple indexes in fac_Department
        $array = array();
        $sql = "SHOW INDEXES FROM fac_Department;";
        foreach ($dbh->query($sql) as $row) {
            $array[$row["Key_name"]] = 1;
        }
        foreach ($array as $key => $garbage) {
            $sql = "ALTER TABLE fac_Department DROP INDEX {$key};";
            $dbh->query($sql);
        }
        $sql = "ALTER TABLE fac_Department ADD PRIMARY KEY (DeptID);";
        $dbh->query($sql);
        $sql = "ALTER TABLE fac_Department ADD UNIQUE KEY Name (Name);";
        $dbh->query($sql);
        // Clean up multiple indexes in fac_DeviceTemplate
        $array = array();
        $sql = "SHOW INDEXES FROM fac_DeviceTemplate;";
        foreach ($dbh->query($sql) as $row) {
            $array[$row["Key_name"]] = 1;
        }
        foreach ($array as $key => $garbage) {
            $sql = "ALTER TABLE fac_Department DROP INDEX {$key};";
            $dbh->query($sql);
        }
        $sql = "ALTER TABLE fac_DeviceTemplate ADD PRIMARY KEY (TemplateID);";
        $dbh->query($sql);
        $sql = "ALTER TABLE fac_DeviceTemplate ADD UNIQUE KEY ManufacturerID (ManufacturerID,Model);";
        $dbh->query($sql);
        // Apply SQL Updates
        $results[] = applyupdate("db-2.0-to-2.1.sql");
        // Add new field for the ConnectionID
        $dbh->query('ALTER TABLE fac_SwitchConnection ADD ConnectionID INT NULL DEFAULT NULL;');
        $sql = "SELECT * FROM fac_SwitchConnection;";
        foreach ($dbh->query($sql) as $row) {
            $insert = "INSERT INTO fac_DevicePorts VALUES (NULL , '{$row['EndpointDeviceID']}', '{$row['EndpointPort']}', NULL , '{$row['Notes']}');";
            $dbh->query($insert);
            $update = "UPDATE fac_SwitchConnection SET ConnectionID='" . $dbh->lastInsertId() . "' WHERE EndpointDeviceID='{$row['EndpointDeviceID']}' AND EndpointPort='{$row['EndpointPort']}';";
            $dbh->query($update);
        }
        // Clear eany old primary key information
        $dbh->query('ALTER TABLE fac_SwitchConnection DROP PRIMARY KEY;');
        // Ensure new ConnectionID is unique
        $dbh->query('ALTER TABLE fac_SwitchConnection ADD UNIQUE(ConnectionID);');
        // Rebuild the config table just in case.  I dunno gremlins.
        $config->rebuild();
        $version = "2.1";
    }
    if ($version == "2.1") {
        // First apply the schema updates needed.
        $results[] = applyupdate("db-2.1-to-3.0.sql");
        print "Update blade devices for new front/rear tracking method<br>\n";
        $sql = "UPDATE fac_Device SET BackSide=1, ChassisSlots=0 WHERE ChassisSlots=1 AND ParentDevice>0;";
        $dbh->query($sql);
        // Port conversion
        $numports = $dbh->query('SELECT SUM(Ports) + (SELECT SUM(Ports) FROM fac_Device WHERE DeviceType="Patch Panel") as TotalPorts, COUNT(DeviceID) as Devices FROM fac_Device')->fetch();
        print "Creating {$numports['TotalPorts']} ports for {$numports['Devices']} devices. <b>THIS MAY TAKE A WHILE</b><br>\n";
        // Retrieve a list of all devices and make ports for them.
        $sql = 'SELECT DeviceID,Ports,DeviceType from fac_Device WHERE 
			DeviceType!="Physical Infrastructure" AND Ports>0;';
        $errors = array();
        $ports = array();
        foreach ($dbh->query($sql) as $row) {
            for ($x = 1; $x <= $row['Ports']; $x++) {
                // Create a port for every device
                $ports[$row['DeviceID']][$x]['Label'] = $x;
                if ($row['DeviceType'] == 'Patch Panel') {
                    // Patch panels needs rear ports as well
                    $ports[$row['DeviceID']][-$x]['Label'] = "Rear {$x}";
                }
            }
        }
        $findswitch = $dbh->prepare('SELECT * FROM fac_SwitchConnection WHERE EndpointDeviceID=:deviceid ORDER BY EndpointPort ASC;');
        foreach ($ports as $deviceid => $port) {
            $findswitch->execute(array(':deviceid' => $deviceid));
            $defined = $findswitch->fetchAll();
            foreach ($defined as $row) {
                // Weed out any port numbers that have been defined outside the range of
                // valid ports for the device
                if (isset($ports[$deviceid][$row['EndpointPort']])) {
                    // Device Ports
                    $ports[$deviceid][$row['EndpointPort']]['Notes'] = $row['Notes'];
                    $ports[$deviceid][$row['EndpointPort']]['Connected Device'] = $row['SwitchDeviceID'];
                    $ports[$deviceid][$row['EndpointPort']]['Connected Port'] = $row['SwitchPortNumber'];
                    // Switch Ports
                    $ports[$row['SwitchDeviceID']][$row['SwitchPortNumber']]['Notes'] = $row['Notes'];
                    $ports[$row['SwitchDeviceID']][$row['SwitchPortNumber']]['Connected Device'] = $row['EndpointDeviceID'];
                    $ports[$row['SwitchDeviceID']][$row['SwitchPortNumber']]['Connected Port'] = $row['EndpointPort'];
                } else {
                    // Either display this as a log item later or possibly backfill empty
                    // ports with this data
                    $errors[$deviceid][$row['EndpointPort']]['Notes'] = $row['Notes'];
                    $errors[$deviceid][$row['EndpointPort']]['Connected Device'] = $row['SwitchDeviceID'];
                    $errors[$deviceid][$row['EndpointPort']]['Connected Port'] = $row['SwitchPortNumber'];
                }
            }
        }
        $findpatch = $dbh->prepare('SELECT * FROM fac_PatchConnection WHERE FrontEndpointDeviceID=:deviceid ORDER BY FrontEndpointPort ASC;');
        foreach ($ports as $deviceid => $port) {
            $findpatch->execute(array(':deviceid' => $deviceid));
            $defined = $findpatch->fetchAll();
            foreach ($defined as $row) {
                // Weed out any port numbers that have been defined outside the range of
                // valid ports for the device
                if (isset($ports[$deviceid][$row['FrontEndpointPort']])) {
                    // Connect the device to the panel
                    $ports[$deviceid][$row['FrontEndpointPort']]['Notes'] = $row['FrontNotes'];
                    $ports[$deviceid][$row['FrontEndpointPort']]['Connected Device'] = $row['PanelDeviceID'];
                    $ports[$deviceid][$row['FrontEndpointPort']]['Connected Port'] = $row['PanelPortNumber'];
                    // Connect the panel to the device
                    $ports[$row['PanelDeviceID']][$row['PanelPortNumber']]['Connected Device'] = $row['FrontEndpointDeviceID'];
                    $ports[$row['PanelDeviceID']][$row['PanelPortNumber']]['Connected Port'] = $row['FrontEndpointPort'];
                    $ports[$row['PanelDeviceID']][$row['PanelPortNumber']]['Notes'] = $row['FrontNotes'];
                } else {
                    // Either display this as a log item later or possibly backfill empty
                    // ports with this data
                    $errors[$deviceid][$row['FrontEndpointPort']]['Notes'] = $row['FrontNotes'];
                    $errors[$deviceid][$row['FrontEndpointPort']]['Connected Device'] = $row['PanelDeviceID'];
                    $errors[$deviceid][$row['FrontEndpointPort']]['Connected Port'] = $row['PanelPortNumber'];
                }
            }
        }
        foreach ($dbh->query('SELECT * FROM fac_PatchConnection;') as $row) {
            // Read all the patch connections again to get the rear connection info
            $ports[$row['RearEndpointDeviceID']][-$row['RearEndpointPort']]['Connected Device'] = $row['PanelDeviceID'];
            $ports[$row['RearEndpointDeviceID']][-$row['RearEndpointPort']]['Connected Port'] = -$row['PanelPortNumber'];
            $ports[$row['RearEndpointDeviceID']][-$row['RearEndpointPort']]['Notes'] = $row['RearNotes'];
            $ports[$row['PanelDeviceID']][-$row['PanelPortNumber']]['Connected Device'] = $row['RearEndpointDeviceID'];
            $ports[$row['PanelDeviceID']][-$row['PanelPortNumber']]['Connected Port'] = -$row['RearEndpointPort'];
            $ports[$row['PanelDeviceID']][-$row['PanelPortNumber']]['Notes'] = $row['RearNotes'];
        }
        // Backfill the extra data
        foreach ($errors as $deviceid => $row) {
            $numPorts = count($ports[$deviceid]) + 1;
            foreach ($row as $portnum => $port) {
                for ($n = 1; $n < $numPorts; $n++) {
                    if (!isset($ports[$deviceid][$n]['Notes'])) {
                        $ports[$deviceid][$n] = $port;
                        // connect up the other side as well
                        $ports[$port['Connected Device']][$port['Connected Port']]['Connected Device'] = $deviceid;
                        $ports[$port['Connected Device']][$port['Connected Port']]['Connected Port'] = $n;
                        $ports[$port['Connected Device']][$port['Connected Port']]['Notes'] = $port['Notes'];
                        unset($errors[$deviceid][$portnum]);
                        // Remove it from the backfill data
                        break;
                    }
                }
            }
        }
        $incdataports = $dbh->prepare('UPDATE fac_Device SET Ports=:n WHERE DeviceID=:deviceid;');
        // Anything left in $errors now is an extra port that exists outside the number of designated deviceports.
        foreach ($errors as $deviceid => $row) {
            foreach ($row as $portnum => $port) {
                $n = count($ports[$deviceid]) + 1;
                $ports[$deviceid][] = $port;
                // connect up the other side as well, $n will give us the new port number
                // since it is outside the defined range for the device
                $ports[$port['Connected Device']][$port['Connected Port']]['Connected Device'] = $deviceid;
                $ports[$port['Connected Device']][$port['Connected Port']]['Connected Port'] = $n;
                $ports[$port['Connected Device']][$port['Connected Port']]['Notes'] = $port['Notes'];
                // Update the number of ports on this device to match the corrected value
                $incdataports->execute(array(":n" => $n, ":deviceid" => $deviceid));
                unset($errors[$deviceid][$portnum]);
                // Remove it from the backfill data
            }
        }
        $n = 1;
        $insertsql = '';
        $insertlimit = 100;
        $insertprogress = 100 / ($numports['TotalPorts'] / $insertlimit);
        $insertprogress = intval($insertprogress) > 0 ? intval($insertprogress) : 1;
        // if this is gonna do more than 100 inserts we might have issues
        echo "<br>\nConversion process: <br>\n<table style=\"border: 1px solid black; border-collapse: collapse; width: 100%;\"><tr>";
        flush();
        // All the ports should be in the array now, use the prepared statement to load them all
        foreach ($ports as $deviceid => $row) {
            foreach ($row as $portnum => $port) {
                $null = null;
                $blank = "";
                $cdevice = isset($port['Connected Device']) ? $port['Connected Device'] : 'NULL';
                $cport = isset($port['Connected Port']) ? $port['Connected Port'] : 'NULL';
                $notes = isset($port['Notes']) ? $port['Notes'] : '';
                $insertsql .= "({$deviceid},{$portnum},\"\",0,0,\"\",{$cdevice},{$cport},\"{$notes}\")";
                if ($n % $insertlimit != 0) {
                    $insertsql .= " ,";
                } else {
                    $dbh->exec('INSERT INTO fac_Ports VALUES' . $insertsql);
                    $insertsql = '';
                    print "<td width=\"{$insertprogress}%\" style=\"background-color: green\">&nbsp;</td>";
                    flush();
                    // attempt to update the progress as this goes on.
                }
                ++$n;
            }
        }
        //do one last insert
        $insertsql = substr($insertsql, 0, -1);
        // shave off that last comma
        $dbh->exec('INSERT INTO fac_Ports VALUES' . $insertsql);
        echo "</tr></table>";
        print "<br>\nPort conversion complete.<br>\n";
        // Rebuild the config table just in case.
        $config->rebuild();
        $version = "3.0";
    }
    if ($version == "3.0") {
        // First apply the schema updates needed.
        $results[] = applyupdate("db-3.0-to-3.1.sql");
        // Rebuild the config table just in case.
        $config->rebuild();
        $version = "3.1";
    }
    if ($version == "3.1") {
        // First apply the schema updates needed.
        $results[] = applyupdate("db-3.1-to-3.2.sql");
        // Rebuild the config table just in case.
        $config->rebuild();
        $version = "3.2";
    }
    if ($version == "3.2") {
        // First apply the schema updates needed.
        $results[] = applyupdate("db-3.2-to-3.3.sql");
        // Rebuild the config table just in case.
        $config->rebuild();
        $version = "3.3";
    }
    if ($version == "3.3") {
        // First apply the schema updates needed.
        $results[] = applyupdate("db-3.3-to-4.0.sql");
        // Rebuild the config table just in case.
        $config->rebuild();
        // We added in some new config items and one of them is referenced in misc.
        // Reload the config;
        $config->Config();
        // We have several things to convert this time around.
        // Bring up the rest of the classes
        require_once "facilities.inc.php";
        // People conversion
        $p = new People();
        $c = new Contact();
        $u = new User();
        $plist = $p->GetUserList();
        // Check if we have an empty fac_People table then merge if that's the case
        if (sizeof($plist) == 0) {
            $clist = $c->GetContactList();
            foreach ($clist as $tmpc) {
                foreach ($tmpc as $prop => $val) {
                    $p->{$prop} = $val;
                }
                // we're keeping the Contact ID so assign it to the PersonID
                $p->PersonID = $tmpc->ContactID;
                $u->UserID = $p->UserID;
                $u->GetUserRights();
                foreach ($u as $prop => $val) {
                    $p->{$prop} = $val;
                }
                // This shouldn't be necessary but...
                $p->MakeSafe();
                $sql = "INSERT INTO fac_People SET PersonID={$p->PersonID}, UserID=\"{$p->UserID}\", \n\t\t\t\t\tAdminOwnDevices={$p->AdminOwnDevices}, ReadAccess={$p->ReadAccess}, \n\t\t\t\t\tWriteAccess={$p->WriteAccess}, DeleteAccess={$p->DeleteAccess}, \n\t\t\t\t\tContactAdmin={$p->ContactAdmin}, RackRequest={$p->RackRequest}, \n\t\t\t\t\tRackAdmin={$p->RackAdmin}, SiteAdmin={$p->SiteAdmin}, Disabled={$p->Disabled}, \n\t\t\t\t\tLastName=\"{$p->LastName}\", FirstName=\"{$p->FirstName}\", \n\t\t\t\t\tPhone1=\"{$p->Phone1}\", Phone2=\"{$p->Phone2}\", Phone3=\"{$p->Phone3}\", \n\t\t\t\t\tEmail=\"{$p->Email}\";";
                $dbh->query($sql);
            }
            $ulist = $u->GetUserList();
            foreach ($ulist as $tmpu) {
                /* This time around we have to see if the User is already in the fac_People table */
                $p->UserID = $tmpu->UserID;
                if (!$p->GetPersonByUserID()) {
                    foreach ($tmpu as $prop => $val) {
                        $p->{$prop} = $val;
                    }
                    // Names have changed formats between the user table and the people table
                    $p->LastName = $tmpu->Name;
                    $p->CreatePerson();
                }
            }
        }
        // END - People conversion
        // CDU template conversion, to be done prior to device conversion
        /*
          I made a poor asumption on the initial build of this that we'd always have fewer
          CDU templates than device templates.  We're seeing an overlap conversion that is 
          screwing the pooch.  This will find the highest template id from the two sets then
          we'll jump the line on the device_template id's and get them lined up.
        */
        $sql = "SELECT TemplateID FROM fac_CDUTemplate UNION SELECT TemplateID FROM \n\t\t\tfac_DeviceTemplate ORDER BY TemplateID DESC LIMIT 1;";
        $baseid = $dbh->query($sql)->fetchColumn();
        class PowerTemplate extends DeviceTemplate
        {
            function CreateTemplate($templateid = null)
            {
                global $dbh;
                $this->MakeSafe();
                $sqlinsert = is_null($templateid) ? '' : " TemplateID={$templateid},";
                $sql = "INSERT INTO fac_DeviceTemplate SET ManufacturerID={$this->ManufacturerID}, \n\t\t\t\t\tModel=\"{$this->Model}\", Height={$this->Height}, Weight={$this->Weight}, \n\t\t\t\t\tWattage={$this->Wattage}, DeviceType=\"{$this->DeviceType}\", \n\t\t\t\t\tSNMPVersion=\"{$this->SNMPVersion}\", PSCount={$this->PSCount}, \n\t\t\t\t\tNumPorts={$this->NumPorts}, Notes=\"{$this->Notes}\", \n\t\t\t\t\tFrontPictureFile=\"{$this->FrontPictureFile}\", \n\t\t\t\t\tRearPictureFile=\"{$this->RearPictureFile}\",{$sqlinsert}\n\t\t\t\t\tChassisSlots={$this->ChassisSlots}, RearChassisSlots={$this->RearChassisSlots};";
                if (!$dbh->exec($sql)) {
                    error_log("SQL Error: " . $sql);
                    return false;
                } else {
                    $this->TemplateID = $dbh->lastInsertId();
                    class_exists('LogActions') ? LogActions::LogThis($this) : '';
                    $this->MakeDisplay();
                    return true;
                }
            }
            static function Convert($row)
            {
                $ct = new stdClass();
                $ct->TemplateID = $row["TemplateID"];
                $ct->ManufacturerID = $row["ManufacturerID"];
                $ct->Model = $row["Model"];
                $ct->PSCount = $row["NumOutlets"];
                $ct->SNMPVersion = $row["SNMPVersion"];
                return $ct;
            }
        }
        $converted = array();
        //index old id, value new id
        $sql = "SELECT * FROM fac_CDUTemplate;";
        foreach ($dbh->query($sql) as $cdutemplate) {
            $ct = PowerTemplate::Convert($cdutemplate);
            $dt = new PowerTemplate();
            $dt->TemplateID = ++$baseid;
            $dt->ManufacturerID = $ct->ManufacturerID;
            $dt->Model = "CDU {$ct->Model}";
            $dt->PSCount = $ct->PSCount;
            $dt->DeviceType = "CDU";
            $dt->SNMPVersion = $ct->SNMPVersion;
            $dt->CreateTemplate($dt->TemplateID);
            $converted[$ct->TemplateID] = $dt->TemplateID;
        }
        // Update all the records with their new templateid
        foreach ($converted as $oldid => $newid) {
            $dbh->query("UPDATE fac_CDUTemplate SET TemplateID={$newid} WHERE TemplateID={$oldid};");
            $dbh->query("UPDATE fac_PowerDistribution SET TemplateID={$newid} WHERE TemplateID={$oldid}");
        }
        // END - CDU template conversion
        // Store a list of existing CDU ids and their converted DeviceID
        $ConvertedCDUs = array();
        // Store a list of the cdu template ids and the number of power connections they support
        $CDUTemplates = array();
        // List of ports we are going to create for every device in the system
        $PowerPorts = array();
        // These should only apply to me but the possibility exists
        $PreNamedPorts = array();
        class PowerDevice extends Device
        {
            /*
            	to be efficient we don't want to create ports right now so we're extending 
            	the class to override the create function
            */
            function CreateDevice()
            {
                global $dbh;
                $this->MakeSafe();
                $this->Label = transform($this->Label);
                $this->SerialNo = transform($this->SerialNo);
                $this->AssetTag = transform($this->AssetTag);
                $sql = "INSERT INTO fac_Device SET Label=\"{$this->Label}\", SerialNo=\"{$this->SerialNo}\", AssetTag=\"{$this->AssetTag}\", \n\t\t\t\t\tPrimaryIP=\"{$this->PrimaryIP}\", SNMPCommunity=\"{$this->SNMPCommunity}\", ESX={$this->ESX}, Owner={$this->Owner}, \n\t\t\t\t\tEscalationTimeID={$this->EscalationTimeID}, EscalationID={$this->EscalationID}, PrimaryContact={$this->PrimaryContact}, \n\t\t\t\t\tCabinet={$this->Cabinet}, Position={$this->Position}, Height={$this->Height}, Ports={$this->Ports}, \n\t\t\t\t\tFirstPortNum={$this->FirstPortNum}, TemplateID={$this->TemplateID}, NominalWatts={$this->NominalWatts}, \n\t\t\t\t\tPowerSupplyCount={$this->PowerSupplyCount}, DeviceType=\"{$this->DeviceType}\", ChassisSlots={$this->ChassisSlots}, \n\t\t\t\t\tRearChassisSlots={$this->RearChassisSlots},ParentDevice={$this->ParentDevice}, \n\t\t\t\t\tMfgDate=\"" . date("Y-m-d", strtotime($this->MfgDate)) . "\", \n\t\t\t\t\tInstallDate=\"" . date("Y-m-d", strtotime($this->InstallDate)) . "\", WarrantyCo=\"{$this->WarrantyCo}\", \n\t\t\t\t\tWarrantyExpire=\"" . date("Y-m-d", strtotime($this->WarrantyExpire)) . "\", Notes=\"{$this->Notes}\", \n\t\t\t\t\tReservation={$this->Reservation}, HalfDepth={$this->HalfDepth}, BackSide={$this->BackSide};";
                if (!$dbh->exec($sql)) {
                    $info = $dbh->errorInfo();
                    error_log("PDO Error: {$info[2]} SQL={$sql}");
                    return false;
                }
                $this->DeviceID = $dbh->lastInsertId();
                class_exists('LogActions') ? LogActions::LogThis($this) : '';
                return $this->DeviceID;
            }
        }
        // Create new devices from existing CDUs
        $sql = "SELECT * FROM fac_PowerDistribution;";
        foreach ($dbh->query($sql) as $row) {
            $dev = new PowerDevice();
            $dev->Label = $row['Label'];
            $dev->Cabinet = $row['CabinetID'];
            $dev->TemplateID = $row['TemplateID'];
            $dev->PrimaryIP = $row['IPAddress'];
            $dev->SNMPCommunity = $row['SNMPCommunity'];
            $dev->Position = 0;
            $dev->Height = 0;
            $dev->Ports = 1;
            if (!isset($CDUTemplates[$dev->TemplateID])) {
                $CDUTemplates[$dev->TemplateID] = $dbh->query("SELECT NumOutlets FROM fac_CDUTemplate WHERE TemplateID={$dev->TemplateID} LIMIT 1;")->fetchColumn();
            }
            $dev->PowerSupplyCount = $CDUTemplates[$dev->TemplateID];
            $dev->PowerSupplyCount;
            $dev->DeviceType = 'CDU';
            $ConvertedCDUs[$row['PDUID']] = $dev->CreateDevice();
        }
        // Create a list of all ports that we need to create, no need to look at children or any device with no defined power supplies
        $sql = "SELECT DeviceID, PowerSupplyCount FROM fac_Device WHERE ParentDevice=0 AND PowerSupplyCount>0;";
        foreach ($dbh->query($sql) as $row) {
            for ($x = 1; $x <= $row['PowerSupplyCount']; $x++) {
                $PowerPorts[$row['DeviceID']][$x]['label'] = $x;
            }
        }
        function workdamnit($numeric = true, &$PreNamedPorts, &$PowerPorts, &$ConvertedCDUs)
        {
            // a PDUID of 0 is considered an error, data fragment, etc.  F**k em, not dealing with em.
            global $dbh;
            $sql = "SELECT * FROM fac_PowerConnection;";
            foreach ($dbh->query($sql) as $row) {
                // something is going stupid so assign everythign to variables
                $pduid = intval($row['PDUID']);
                $pdupos = $row['PDUPosition'];
                $devid = intval($row['DeviceID']);
                $devcon = $row['DeviceConnNumber'];
                $newpduid = $ConvertedCDUs[$pduid];
                $port = '';
                if (is_numeric($pdupos) && $numeric && $pduid > 0) {
                    $port = $pdupos;
                } elseif (!is_numeric($pdupos) && !$numeric && $pduid > 0) {
                    $newPDUID = $newpduid;
                    if (!isset($PreNamedPorts[$newPDUID][$pdupos])) {
                        // Move the array pointer to the end of the ports array
                        end($PowerPorts[$newPDUID]);
                        $max = key($PowerPorts[$newPDUID]);
                        ++$max;
                        // Create a new port for the named port, this will likely extend past the valid amount of ports on the device.
                        $PowerPorts[$newPDUID][$max]['label'] = $pdupos;
                        // Store a pointer between the name and new port index
                        $PreNamedPorts[$newPDUID][$pdupos] = $max;
                    }
                    $port = $PreNamedPorts[$newPDUID][$pdupos];
                }
                if (is_numeric($pdupos) && $numeric || !is_numeric($pdupos) && !$numeric && $pduid > 0) {
                    // Create primary connections
                    $PowerPorts[$devid][$devcon]['ConnectedDeviceID'] = $newpduid;
                    $PowerPorts[$devid][$devcon]['ConnectedPort'] = $port;
                    // Create reverse of primary
                    $PowerPorts[$newpduid][$port]['ConnectedDeviceID'] = $devid;
                    $PowerPorts[$newpduid][$port]['ConnectedPort'] = $devcon;
                }
            }
        }
        // We need to get a list of all existing power connections
        workdamnit(true, $PreNamedPorts, $PowerPorts, $ConvertedCDUs);
        // First time through setting up all numeric ports
        workdamnit(false, $PreNamedPorts, $PowerPorts, $ConvertedCDUs);
        // Run through again but this time only deal with named ports and append them to the end of the numeric
        /* 
        * Debug Info
        
        		print "Converted CDUs:\n<br>";
        		print_r($ConvertedCDUs);
        
        		print "Port list:\n<br>";
        		print_r($PowerPorts);
        
        		print "SQL entries:\n<br>";
        */
        $n = 1;
        $insertsql = '';
        $insertlimit = 100;
        foreach ($PowerPorts as $DeviceID => $PowerPort) {
            foreach ($PowerPort as $PortNum => $PortDetails) {
                $label = isset($PortDetails['label']) ? $PortDetails['label'] : $PortNum;
                $cdevice = isset($PortDetails['ConnectedDeviceID']) ? $PortDetails['ConnectedDeviceID'] : 'NULL';
                $cport = isset($PortDetails['ConnectedPort']) ? $PortDetails['ConnectedPort'] : 'NULL';
                $insertsql .= "({$DeviceID},{$PortNum},\"{$label}\",{$cdevice},{$cport},\"\")";
                if ($n % $insertlimit != 0) {
                    $insertsql .= " ,";
                } else {
                    $dbh->exec('INSERT INTO fac_PowerPorts VALUES' . $insertsql);
                    // Debug for sql
                    //					print "$insertsql\n\n<br><br>";
                    //					print_r($dbh->errorInfo());
                    $insertsql = '';
                }
                $n++;
            }
        }
        //do one last insert
        $insertsql = substr($insertsql, 0, -1);
        // shave off that last comma
        $dbh->exec('INSERT INTO fac_PowerPorts VALUES' . $insertsql);
        // Debug for sql
        //					print "$insertsql\n\n<br><br>";
        //					print_r($dbh->errorInfo());
        // Update all the records with their new deviceid
        foreach ($ConvertedCDUs as $oldid => $newid) {
            $dbh->query("UPDATE fac_PowerDistribution SET PDUID = '{$newid}' WHERE PDUID={$oldid};");
        }
        // Since we moved SNMPVersion out of the subtemplates and into the main one, we need one last cleanup
        $st = $dbh->prepare("select * from fac_DeviceTemplate where DeviceType='CDU'");
        $st->execute();
        $up = $dbh->prepare("update fac_Device set SNMPVersion=:SNMPVersion where TemplateID=:TemplateID");
        while ($row = $st->fetch()) {
            $up->execute(array(":SNMPVersion" => $row["SNMPVersion"], ":TemplateID" => $row["TemplateID"]));
        }
        // END - CDU template conversion, to be done prior to device conversion
        // Sensor template conversion
        // Step one - convert individual SensorTemplates into just Templates
        $s = $dbh->prepare("select * from fac_SensorTemplate");
        $s->execute();
        while ($row = $s->fetch()) {
            // Create fresh instances
            $st = new SensorTemplate();
            $dt = new DeviceTemplate();
            $dt->ManufacturerID = $row["ManufacturerID"];
            $dt->Model = $row["Model"];
            $dt->Height = 0;
            $dt->Weight = 0;
            $dt->Wattage = 0;
            $dt->DeviceType = "Sensor";
            $dt->PSCount = 0;
            $dt->NumPorts = 0;
            $dt->Notes = "Converted from version 3.3 format.";
            $dt->FrontPictureFile = '';
            $dt->RearPictureFile = '';
            $dt->ChassisSlots = 0;
            $dt->RearChassisSlots = 0;
            $dt->CreateTemplate();
            // The DeviceTemplate::CreateTemplate() method created a new SensorTemplate already
            if ($dt->TemplateID < 1) {
                error_log("DeviceTemplate creation failed.");
            } else {
                $st->TemplateID = $dt->TemplateID;
                $st->GetTemplate();
                $st->SNMPVersion = $row["SNMPVersion"];
                $st->TemperatureOID = $row["TemperatureOID"];
                $st->HumidityOID = $row["HumidityOID"];
                $st->TempMultiplier = $row["TempMultiplier"];
                $st->HumidityMultiplier = $row["HumidityMultiplier"];
                $st->mUnits = $row["mUnits"];
                $st->UpdateTemplate();
                // Even though this is just temporary, update all existing references to the new TemplateID
                $sql = "update fac_Cabinet set SensorTemplateID=:NewID where SensorTemplateID=:OldID";
                $q = $dbh->prepare($sql);
                $q->execute(array(":NewID" => $dt->TemplateID, ":OldID" => $row["TemplateID"]));
                // Delete the original template entry in the fac_SensorTemplate table
                $st->TemplateID = $row["TemplateID"];
                $st->DeleteTemplate();
            }
        }
        $ds = $dbh->prepare("alter table fac_SensorTemplate drop column SNMPVersion");
        // Step two - pull sensors from the Cabinets and create as new devices
        $s = $dbh->prepare("select * from fac_Cabinet where SensorIPAddress!=''");
        $s->execute();
        while ($row = $s->fetch()) {
            $dev = new Device();
            $dev->Label = $row["Location"] . " - Sensor";
            $dev->SNMPCommunity = $row["SensorCommunity"];
            $dev->PrimaryIP = $row["SensorIPAddress"];
            $dev->TemplateID = $row["SensorTemplateID"];
            $dev->DeviceType = "Sensor";
            $dev->Cabinet = $row["CabinetID"];
            $dev->CreateDevice();
        }
        // END - Sensor template conversion
        // Power panel conversion
        $dbh->beginTransaction();
        $ss = $dbh->prepare("select * from fac_PowerSource");
        $ss->execute();
        $ps = $dbh->prepare("insert into fac_PowerPanel set PanelLabel=:PanelLabel");
        $us = $dbh->prepare("update fac_PowerPanel set ParentPanelID=:PanelID where PowerSourceID=:SourceID");
        while ($row = $ss->fetch()) {
            $ps->execute(array(":PanelLabel" => $row["SourceName"]));
            $us->execute(array(":PanelID" => $dbh->LastInsertId(), ":SourceID" => $row["PowerSourceID"]));
        }
        $dbh->commit();
        // END - Power panel conversion
        // Get rid of the original PowerSource table since it is no longer in use
        $drop = $dbh->prepare("drop table fac_PowerSource");
        $drop->execute();
        $drop = $dbh->prepare("alter table fac_PowerPanel drop column PowerSourceID");
        $drop->execute();
        // Make sure all child devices have updated cabinet information
        $sql = "SELECT DISTINCT ParentDevice AS DeviceID FROM fac_Device WHERE \n\t\t\tParentDevice>0 ORDER BY ParentDevice ASC;";
        foreach ($dbh->query($sql) as $row) {
            $d = new Device();
            $d->DeviceID = $row['DeviceID'];
            $d->GetDevice();
            $d->UpdateDevice();
        }
        $version = "4.0";
    }
    if ($version == "4.0") {
        // First apply the schema updates needed.
        $results[] = applyupdate("db-4.0-to-4.0.1.sql");
        // Rebuild the config table just in case.
        $config->rebuild();
    }
}
Example #19
0
<?php

require 'model/model.php';
require 'dbConnection.php';
$conn = mysqli_connect(SERVER_ADDRESS, USER_NAME, PASSWORD, DATABASE);
$id = $match[1];
$token = $match[2];
$verification = People::verifyEmail($id, $token, $conn);
mysqli_close($conn);
// header('Content-type: application/json');
// echo json_encode($verification);
include 'controller/Verify.html';
Example #20
0
//			readaccess, writeaccess, deleteaccess, contactadmin, rackrequest,
//			rackadmin, siteadmin
//	Returns: record as created
//
$app->put('/people/:userid', function ($userid) use($app, $person) {
    if (!$person->ContactAdmin) {
        $response['error'] = true;
        $response['errorcode'] = 400;
        $response['message'] = "Insufficient privilege level";
        echoResponse(200, $response);
        $app->stop();
    }
    // Only one field is required - all others are optional
    verifyRequiredParams(array('UserID'));
    $response = array();
    $p = new People();
    $p->UserID = $app->request->put('UserID');
    if ($p->GetPersonByUserID()) {
        $response['error'] = true;
        $response['errorcode'] = 403;
        $response['message'] = __("UserID already in database.  Use the update API to modify record.");
        echoResponse(200, $response);
    } else {
        // Slim Framework will simply return null for any variables that were not passed, so this is safe to call without blowing up the script
        foreach ($p as $prop) {
            $p->{$prop} = $app->request->put($prop);
        }
        $p->Disabled = false;
        $p->CreatePerson();
        if ($p->PersonID == false) {
            $response['error'] = true;
Example #21
0
<?php

require_once 'db.inc.php';
require_once 'facilities.inc.php';
$subheader = __("Data Center Virtual Machine Detail");
if (!$person->WriteAccess || !isset($_REQUEST['vmindex'])) {
    // No soup for you.
    header('Location: ' . redirect());
    exit;
}
$dept = new Department();
$esx = new ESX();
$con = new People();
$dev = new Device();
if ($_REQUEST['vmindex'] > 0) {
    $esx->VMIndex = $_REQUEST['vmindex'];
    $esx->GetVMbyIndex();
    $dev->DeviceID = $esx->DeviceID;
    $dev->GetDevice();
    if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'Update') {
        $esx->Owner = $_REQUEST['owner'];
        $esx->PrimaryContact = $_REQUEST['contact'];
        $esx->UpdateVMOwner();
        header('Location: ' . redirect("devices.php?DeviceID={$esx->DeviceID}"));
    }
} else {
    // How'd you get here without a valid vmindex?
    header('Location: ' . redirect());
    exit;
}
$contactList = $con->GetUserList();
require 'model/model.php';
require 'dbConnection.php';
$userID = $match[1];
$conn = mysqli_connect(SERVER_ADDRESS, USER_NAME, PASSWORD, DATABASE);
$user = People::getUser($userID, $conn);
if ($user[0] != 1) {
    mysqli_close($conn);
    header('Content-type: application/json');
    echo json_encode(array("status" => false, "msg" => $user[1]));
    die;
}
$user = $user[1];
$loginInfo = People::getUserLoginInfo($userID, $conn);
if ($loginInfo[0] != 1) {
    mysqli_close($conn);
    header('Content-type: application/json');
    echo json_encode(array("status" => false, "msg" => "Error! Contact Registration Desk Immediately."));
    die;
}
mysqli_close($conn);
$loginInfo = $loginInfo[1];
if (is_null($loginInfo['password'])) {
    header('Content-type: application/json');
    echo json_encode(array("status" => false, "msg" => "Account already verified."));
    die;
}
People::Email($user['email'], $user['name'], $loginInfo['csrfToken'], $userID);
header('Content-type: application/json');
echo json_encode(array("status" => true, "msg" => "Verification link sent to registered email."));
die;
 public function workflowAction()
 {
     if ($this->getParam('id', false)) {
         $people = new People();
         $exist = $people->checkEmailOwner($this->getParam('id'));
         $person = $this->getAccount();
         $from = array('name' => $person->fullname, 'email' => $person->email);
         $this->view->from = $exist;
         $form = new ChangeWorkFlowForm();
         $findStatus = $this->getFinds()->fetchRow($this->getFinds()->select()->where('id = ?', $this->getParam('id')));
         $this->view->details = $findStatus;
         $this->view->find = $findStatus->old_findID;
         $form->populate($findStatus->toArray());
         $this->view->form = $form;
         if (!empty($exist)) {
             if (is_null($exist['0']['email'])) {
                 $form->finder->setAttrib('disabled', 'disabled');
                 $form->finder->setDescription('No email associated with finder yet.');
                 $form->removeElement('content');
             }
         }
         if ($this->getRequest()->isPost()) {
             if ($form->isValid($this->_request->getPost())) {
                 $updateData = array('secwfstage' => $form->getValue('secwfstage'));
                 if (strlen($form->getValue('finder')) > 0) {
                     $assignData = array('name' => $exist['0']['name'], 'old_findID' => $findStatus->old_findID, 'id' => $this->getParam('id'), 'from' => $person->fullname, 'workflow' => $form->getValue('secwfstage'), 'content' => $form->getValue('content'));
                     $this->_helper->mailer($assignData, 'informFinderWorkflow', $exist, array($from), array($from), null, null);
                 }
                 $where = array();
                 $where[] = $this->getFinds()->getAdapter()->quoteInto('id = ?', $this->getParam('id'));
                 $this->getFinds()->update($updateData, $where);
                 $this->_helper->audit($updateData, $findStatus->toArray(), 'FindsAudit', $this->getParam('findID'), $this->getParam('findID'));
                 $this->_helper->solrUpdater->update('objects', $this->getParam('id'), 'artefacts');
                 $this->getFlash()->addMessage('Workflow status changed');
                 $this->redirect('database/artefacts/record/id/' . $this->getParam('id'));
                 $this->_request->setMethod('GET');
             } else {
                 $this->getFlash()->addMessage('There were problems changing the workflow');
                 $form->populate($this->_request->getPost());
             }
         }
     } else {
         throw new Pas_Exception_Param($this->_missingParameter, 500);
     }
 }
Example #24
0
<?php

require 'model/model.php';
require 'dbConnection.php';
$conn = mysqli_connect(SERVER_ADDRESS, USER_NAME, PASSWORD, DATABASE);
require 'middleware/authMiddleware.php';
$userID = $_SESSION['userID'];
$eveID = $match[1];
$size = Events::getEventSize($eveID, $conn);
if ($size == -1) {
    mysqli_close($conn);
    header('Content-type: application/json');
    echo json_encode(array("status" => false, "msg" => "Event does not exist!"));
    die;
} elseif ($size != 1) {
    mysqli_close($conn);
    header('Content-type: application/json');
    echo json_encode(array("status" => false, "msg" => "Registration not allowed!"));
    die;
}
$result = People::registerEventUserSingle($userID, $eveID, $conn);
mysqli_close($conn);
header('Content-type: application/json');
echo json_encode($result);
	<div class="page">
<?php 
    include 'sidebar.inc.php';
    echo '		<div class="main">
			<div class="center">
				<div id="tablecontainer">';
    //
    //
    //	Begin Report Generation
    //
    //
    $pan = new PowerPanel();
    $pdu = new PowerDistribution();
    $dev = new Device();
    $cab = new Cabinet();
    $tmpPerson = new People();
    $dept = new Department();
    $dc = new DataCenter();
    // Make some quick user defined sort comparisons for this report only
    function compareCab($a, $b)
    {
        if ($a->Location == $b->Location) {
            return 0;
        }
        return $a->Location > $b->Location ? +1 : -1;
    }
    $dc->DataCenterID = intval($_REQUEST['datacenterid']);
    $dc->GetDataCenter();
    $skipNormal = false;
    if (isset($_REQUEST["skipnormal"])) {
        $skipNormal = $_REQUEST["skipnormal"];
Example #26
0
 protected function _executeTestsNormal($di)
 {
     $this->_prepareDb($di->getShared('db'));
     //Count tests
     $this->assertEquals(People::count(), Personas::count());
     $params = array();
     $this->assertEquals(People::count($params), Personas::count($params));
     $params = array("estado='I'");
     $this->assertEquals(People::count($params), Personas::count($params));
     $params = "estado='I'";
     $this->assertEquals(People::count($params), Personas::count($params));
     $params = array("conditions" => "estado='I'");
     $this->assertEquals(People::count($params), Personas::count($params));
     //Find first
     $people = People::findFirst();
     $this->assertTrue(is_object($people));
     $this->assertEquals(get_class($people), 'People');
     $persona = Personas::findFirst();
     $this->assertEquals($people->nombres, $persona->nombres);
     $this->assertEquals($people->estado, $persona->estado);
     $people = People::findFirst("estado='I'");
     $this->assertTrue(is_object($people));
     $persona = Personas::findFirst("estado='I'");
     $this->assertTrue(is_object($persona));
     $this->assertEquals($people->nombres, $persona->nombres);
     $this->assertEquals($people->estado, $persona->estado);
     $people = People::findFirst(array("estado='I'"));
     $persona = Personas::findFirst(array("estado='I'"));
     $this->assertEquals($people->nombres, $persona->nombres);
     $this->assertEquals($people->estado, $persona->estado);
     $params = array("conditions" => "estado='I'");
     $people = People::findFirst($params);
     $persona = Personas::findFirst($params);
     $this->assertEquals($people->nombres, $persona->nombres);
     $this->assertEquals($people->estado, $persona->estado);
     $params = array("conditions" => "estado='A'", "order" => "nombres");
     $people = People::findFirst($params);
     $persona = Personas::findFirst($params);
     $this->assertEquals($people->nombres, $persona->nombres);
     $this->assertEquals($people->estado, $persona->estado);
     $params = array("estado='A'", "order" => "nombres DESC", "limit" => 30);
     $people = People::findFirst($params);
     $persona = Personas::findFirst($params);
     $this->assertEquals($people->nombres, $persona->nombres);
     $this->assertEquals($people->estado, $persona->estado);
     $params = array("estado=?1", "bind" => array(1 => 'A'), "order" => "nombres DESC", "limit" => 30);
     $people = People::findFirst($params);
     $persona = Personas::findFirst($params);
     $this->assertEquals($people->nombres, $persona->nombres);
     $this->assertEquals($people->estado, $persona->estado);
     $params = array("estado=:estado:", "bind" => array("estado" => 'A'), "order" => "nombres DESC", "limit" => 30);
     $people = People::findFirst($params);
     $persona = Personas::findFirst($params);
     $this->assertEquals($people->nombres, $persona->nombres);
     $this->assertEquals($people->estado, $persona->estado);
     $robot = Robots::findFirst(1);
     $this->assertEquals(get_class($robot), 'Robots');
     //Find tests
     $personas = Personas::find();
     $people = People::find();
     $this->assertEquals(count($personas), count($people));
     $personas = Personas::find("estado='I'");
     $people = People::find("estado='I'");
     $this->assertEquals(count($personas), count($people));
     $personas = Personas::find(array("estado='I'"));
     $people = People::find(array("estado='I'"));
     $this->assertEquals(count($personas), count($people));
     $personas = Personas::find(array("estado='A'", "order" => "nombres"));
     $people = People::find(array("estado='A'", "order" => "nombres"));
     $this->assertEquals(count($personas), count($people));
     $personas = Personas::find(array("estado='A'", "order" => "nombres", "limit" => 100));
     $people = People::find(array("estado='A'", "order" => "nombres", "limit" => 100));
     $this->assertEquals(count($personas), count($people));
     $params = array("estado=?1", "bind" => array(1 => "A"), "order" => "nombres", "limit" => 100);
     $personas = Personas::find($params);
     $people = People::find($params);
     $this->assertEquals(count($personas), count($people));
     $params = array("estado=:estado:", "bind" => array("estado" => "A"), "order" => "nombres", "limit" => 100);
     $personas = Personas::find($params);
     $people = People::find($params);
     $this->assertEquals(count($personas), count($people));
     $number = 0;
     $peoples = Personas::find(array("conditions" => "estado='A'", "order" => "nombres", "limit" => 20));
     foreach ($peoples as $people) {
         $number++;
     }
     $this->assertEquals($number, 20);
     $persona = new Personas($di);
     $persona->cedula = 'CELL' . mt_rand(0, 999999);
     $this->assertFalse($persona->save());
     //Messages
     $this->assertEquals(count($persona->getMessages()), 4);
     $messages = array(0 => ModelMessage::__set_state(array('_type' => 'PresenceOf', '_message' => 'tipo_documento_id is required', '_field' => 'tipo_documento_id')), 1 => ModelMessage::__set_state(array('_type' => 'PresenceOf', '_message' => 'nombres is required', '_field' => 'nombres')), 2 => ModelMessage::__set_state(array('_type' => 'PresenceOf', '_message' => 'cupo is required', '_field' => 'cupo')), 3 => ModelMessage::__set_state(array('_type' => 'PresenceOf', '_message' => 'estado is required', '_field' => 'estado')));
     $this->assertEquals($persona->getMessages(), $messages);
     //Save
     $persona = new Personas($di);
     $persona->cedula = 'CELL' . mt_rand(0, 999999);
     $persona->tipo_documento_id = 1;
     $persona->nombres = 'LOST';
     $persona->telefono = '1';
     $persona->cupo = 20000;
     $persona->estado = 'A';
     $this->assertTrue($persona->save());
     $persona = new Personas($di);
     $persona->cedula = 'CELL' . mt_rand(0, 999999);
     $persona->tipo_documento_id = 1;
     $persona->nombres = 'LOST LOST';
     $persona->telefono = '2';
     $persona->cupo = 0;
     $persona->estado = 'X';
     $this->assertTrue($persona->save());
     //Check correct save
     $persona = Personas::findFirst(array("estado='X'"));
     $this->assertNotEquals($persona, false);
     $this->assertEquals($persona->nombres, 'LOST LOST');
     $this->assertEquals($persona->estado, 'X');
     //Update
     $persona->cupo = 150000;
     $persona->telefono = '123';
     $this->assertTrue($persona->update());
     //Checking correct update
     $persona = Personas::findFirst(array("estado='X'"));
     $this->assertNotEquals($persona, false);
     $this->assertEquals($persona->cupo, 150000);
     $this->assertEquals($persona->telefono, '123');
     //Update
     $this->assertTrue($persona->update(array('nombres' => 'LOST UPDATE', 'telefono' => '2121')));
     //Checking correct update
     $persona = Personas::findFirst(array("estado='X'"));
     $this->assertNotEquals($persona, false);
     $this->assertEquals($persona->nombres, 'LOST UPDATE');
     $this->assertEquals($persona->telefono, '2121');
     //Create
     $persona = new Personas($di);
     $persona->cedula = 'CELL' . mt_rand(0, 999999);
     $persona->tipo_documento_id = 1;
     $persona->nombres = 'LOST CREATE';
     $persona->telefono = '1';
     $persona->cupo = 21000;
     $persona->estado = 'A';
     $this->assertTrue($persona->create());
     $persona = new Personas($di);
     $this->assertTrue($persona->create(array('cedula' => 'CELL' . mt_rand(0, 999999), 'tipo_documento_id' => 1, 'nombres' => 'LOST CREATE', 'telefono' => '1', 'cupo' => 21000, 'estado' => 'A')));
     //Grouping
     $difEstados = People::count(array("distinct" => "estado"));
     $this->assertEquals($difEstados, 3);
     $group = People::count(array("group" => "estado"));
     $this->assertEquals(count($group), 3);
     //Deleting
     $before = People::count();
     $this->assertTrue($persona->delete());
     $this->assertEquals($before - 1, People::count());
     //Assign
     $persona = new Personas();
     $persona->assign(array('tipo_documento_id' => 1, 'nombres' => 'LOST CREATE', 'telefono' => '1', 'cupo' => 21000, 'estado' => 'A', 'notField' => 'SOME VALUE'));
     $expected = array('cedula' => NULL, 'tipo_documento_id' => 1, 'nombres' => 'LOST CREATE', 'telefono' => '1', 'direccion' => NULL, 'email' => NULL, 'fecha_nacimiento' => NULL, 'ciudad_id' => NULL, 'creado_at' => NULL, 'cupo' => 21000, 'estado' => 'A');
     $this->assertEquals($persona->toArray(), $expected);
     //Refresh
     $persona = Personas::findFirst();
     $personaData = $persona->toArray();
     $persona->assign(array('tipo_documento_id' => 1, 'nombres' => 'LOST CREATE', 'telefono' => '1', 'cupo' => 21000, 'estado' => 'A', 'notField' => 'SOME VALUE'));
     $persona->refresh();
     $this->assertEquals($personaData, $persona->toArray());
     // Issue 1314
     $parts = new Parts2();
     $parts->save();
 }
Example #27
0
 protected function _executeTestsNormal($di)
 {
     //Where
     $personas = Personas::query()->where("estado='I'")->execute();
     $people = People::find("estado='I'");
     $this->assertEquals(count($personas), count($people));
     $personas = Personas::query()->conditions("estado='I'")->execute();
     $people = People::find("estado='I'");
     $this->assertEquals(count($personas), count($people));
     $personas = Personas::query()->where("estado='A'")->orderBy("nombres")->execute();
     $people = People::find(array("estado='A'", "order" => "nombres"));
     $this->assertEquals(count($personas), count($people));
     $somePersona = $personas->getFirst();
     $somePeople = $people->getFirst();
     $this->assertEquals($somePersona->cedula, $somePeople->cedula);
     //Where + Order + limit
     $personas = Personas::query()->where("estado='A'")->orderBy("nombres")->limit(100)->execute();
     $people = People::find(array("estado='A'", "order" => "nombres", "limit" => 100));
     $this->assertEquals(count($personas), count($people));
     $somePersona = $personas->getFirst();
     $somePeople = $people->getFirst();
     $this->assertEquals($somePersona->cedula, $somePeople->cedula);
     //Where with bind params + order + Limit
     $personas = Personas::query()->where("estado=?1")->bind(array(1 => "A"))->orderBy("nombres")->limit(100)->execute();
     $people = People::find(array("estado=?1", "bind" => array(1 => "A"), "order" => "nombres", "limit" => 100));
     $this->assertEquals(count($personas), count($people));
     $somePersona = $personas->getFirst();
     $somePeople = $people->getFirst();
     $this->assertEquals($somePersona->cedula, $somePeople->cedula);
     //Where with bind params + order + limit + Offset
     $personas = Personas::query()->where("estado=?1")->bind(array(1 => "A"))->orderBy("nombres")->limit(100, 10)->execute();
     $people = People::find(array("estado=?1", "bind" => array(1 => "A"), "order" => "nombres", "limit" => array('number' => 100, 'offset' => 10)));
     $this->assertEquals(count($personas), count($people));
     $somePersona = $personas->getFirst();
     $somePeople = $people->getFirst();
     $this->assertEquals($somePersona->cedula, $somePeople->cedula);
     //Where with named bind params + order + limit
     $personas = Personas::query()->where("estado=:estado:")->bind(array("estado" => "A"))->orderBy("nombres")->limit(100)->execute();
     $people = People::find(array("estado=:estado:", "bind" => array("estado" => "A"), "order" => "nombres", "limit" => 100));
     $this->assertEquals(count($personas), count($people));
     $somePersona = $personas->getFirst();
     $somePeople = $people->getFirst();
     $this->assertEquals($somePersona->cedula, $somePeople->cedula);
 }
Example #28
0
    header('Content-type: application/json');
    echo json_encode(array("status" => false, "msg" => "Incomplete request. Team name missing."));
    die;
}
$eveID = $match[1];
$size = Events::getEventSize($eveID, $conn);
if ($size == -1) {
    mysqli_close($conn);
    header('Content-type: application/json');
    echo json_encode(array("status" => false, "msg" => "Event does not exist!"));
    die;
} elseif ($size == 1) {
    mysqli_close($conn);
    header('Content-type: application/json');
    echo json_encode(array("status" => false, "msg" => "This is not a group Event."));
    die;
}
for ($i = 0; $i < count($userIDs); $i++) {
    if (Auth::sanitizeID($userIDs[$i])['status']) {
        $userIDs[$i] = Auth::sanitizeID($userIDs[$i])['key'];
    } else {
        header('Content-type: application/json');
        echo json_encode(array("status" => false, "msg" => "ID is not valid " . $userIDs[$i]));
        die;
    }
}
array_push($userIDs, $userID);
$result = People::registerGroupEvent($userIDs, $size, $eveID, $name, $conn);
mysqli_close($conn);
header('Content-type: application/json');
echo json_encode($result);
Example #29
0
function foo(People $obj)
{
    $obj->sayName();
    $obj->eat();
}
Example #30
0
 protected function _executeTestsNormal($di)
 {
     $number = 0;
     $robots = Robots::find();
     foreach ($robots as $robot) {
         $this->assertTrue(is_object($robot));
         $this->assertEquals(get_class($robot), 'Robots');
         $number++;
     }
     $robots->setHydrateMode(Phalcon\Mvc\Model\Resultset::HYDRATE_RECORDS);
     foreach ($robots as $robot) {
         $this->assertTrue(is_object($robot));
         $this->assertEquals(get_class($robot), 'Robots');
         $number++;
     }
     $robots->setHydrateMode(Phalcon\Mvc\Model\Resultset::HYDRATE_ARRAYS);
     foreach ($robots as $robot) {
         $this->assertTrue(is_array($robot));
         $this->assertEquals(count($robot), 4);
         $number++;
     }
     $robots->setHydrateMode(Phalcon\Mvc\Model\Resultset::HYDRATE_OBJECTS);
     foreach ($robots as $robot) {
         $this->assertTrue(is_object($robot));
         $this->assertEquals(get_class($robot), 'stdClass');
         $number++;
     }
     $this->assertEquals($number, 12);
     $number = 0;
     $people = People::find(array('limit' => 33));
     foreach ($people as $person) {
         $this->assertTrue(is_object($person));
         $this->assertEquals(get_class($person), 'People');
         $number++;
     }
     $people->setHydrateMode(Phalcon\Mvc\Model\Resultset::HYDRATE_RECORDS);
     foreach ($people as $person) {
         $this->assertTrue(is_object($person));
         $this->assertEquals(get_class($person), 'People');
         $number++;
     }
     $people->setHydrateMode(Phalcon\Mvc\Model\Resultset::HYDRATE_ARRAYS);
     foreach ($people as $person) {
         $this->assertTrue(is_array($person));
         $number++;
     }
     $people->setHydrateMode(Phalcon\Mvc\Model\Resultset::HYDRATE_OBJECTS);
     foreach ($people as $person) {
         $this->assertTrue(is_object($person));
         $this->assertEquals(get_class($person), 'stdClass');
         $number++;
     }
     $this->assertEquals($number, 33 * 4);
 }