Beispiel #1
0
 /**
  * {@inheritdoc}
  */
 public function log($level, $message, array $context = array())
 {
     $trigger = ['%type' => 'Exception', '@message' => 'Deforestation', '%function' => 'Drupal\\error_service_test\\MonkeysInTheControlRoom->handle()', 'severity_level' => 3, 'channel' => 'php'];
     if (array_diff_assoc($trigger, $context) === []) {
         throw new \Exception('Oh, oh, frustrated monkeys!');
     }
 }
 public function afterSave($event)
 {
     $modelKey = $this->getOwner()->getPrimaryKey();
     if (!is_array($modelKey) && $this->_notSelf()) {
         $newAttributes = $this->getOwner()->getAttributes();
         $oldAttributes = $this->getOldAttributes();
         $diffAttributes = array_diff_assoc($newAttributes, $oldAttributes);
         $log = new $this->systemLog();
         $log->controller_id = $this->controllerId;
         $log->model_id = $this->modelId;
         $log->user_id = Yii::app()->user->id;
         $log->model_pk_id = $modelKey;
         $log->event = $this->getOwner()->isNewRecord ? 'create' : 'update';
         $log->source = 'web';
         $log->save();
         if (!empty($diffAttributes)) {
             foreach ($diffAttributes as $k => $v) {
                 $change = new $this->systemLogChange();
                 $change->system_log_id = $log->id;
                 $change->column = $k;
                 $change->value = $v;
                 $change->save();
             }
         }
     }
 }
Beispiel #3
0
/**
 * @param string $a
 * @param string $b
 * @return int distance
 */
function distance($a, $b)
{
    if (strlen($a) !== strlen($b)) {
        throw new InvalidArgumentException('DNA strands must be of equal length.');
    }
    return count(array_diff_assoc(str_split($a), str_split($b)));
}
Beispiel #4
0
 function _before_update(&$data, $options)
 {
     $old_data = M("Crm")->find($data['id']);
     $diff = array_diff_assoc($data, $old_data);
     $diff = array_keys($diff);
     $desc = array('name' => '姓名', 'mobile_tel' => '手机', 'district' => '小区', 'need' => '客户需求', 'source' => '客户来源', 'age' => '年龄', 'work' => '职业');
     if (!empty($diff)) {
         foreach ($diff as $val) {
             $model->need = implode(",", $model->need);
             if (is_array($data[$val])) {
                 $new = implode(",", $data[$val]);
             } else {
                 $new = $data[$val];
             }
             $comment .= $desc[$val] . ":" . $old_data[$val] . "->" . $new . " ;  ";
         }
         $model = D("CrmLog");
         $log['user_id'] = get_user_id();
         $log['user_name'] = get_user_name();
         $log['create_time'] = time();
         $log['crm_id'] = $data['id'];
         $log['emp_no'] = get_emp_no();
         $log['comment'] = $comment;
         $model->add($log);
     }
 }
Beispiel #5
0
 /**
  * The real stuff !
  */
 public function assertChanges($test, &$initialData, &$finalData, $msg = null)
 {
     if (count($this->changes) == 0 && count($this->ignoredElements) == 0) {
         if ($initialData !== $finalData) {
             $diff1 = array_diff_assoc($initialData, $finalData);
             $diff2 = array_diff_assoc($finalData, $initialData);
             $test->fail(($msg !== null ? $msg . "\n" : '') . 'Unexpected changes on ' . $this->getElementDesc() . ': ' . var_export(array('initial' => $diff1, 'final' => $diff2), true));
         }
     } else {
         foreach ($this->properties as $propName) {
             if (in_array($propName, $this->ignoredElements)) {
                 continue;
             }
             $change = $this->getChangeByPropertyName($propName);
             if ($change === null) {
                 if ($this->debug) {
                     echo 'Quick check ' . get_class($this) . " on " . $propName . "\n";
                 }
                 $initialValue = $initialData[$propName];
                 $finalValue = $finalData[$propName];
                 if (!yTest_isEqual($initialValue, $finalValue)) {
                     $test->fail(($msg !== null ? $msg . "\n" : '') . 'Unexpected change on ' . $this->getElementDesc() . '->' . $propName . ': initial=' . $initialValue . ' final=' . $finalValue);
                 }
             }
         }
     }
     foreach ($this->changes as $change) {
         if ($this->debug) {
             echo "assert " . $change . "\n";
         }
         $change->assertChange($test, $initialData[$change->getInfoName()], $finalData[$change->getInfoName()], $msg);
     }
 }
 function _processSave(&$controller, &$xoopsUser)
 {
     $moduleHandler =& xoops_gethandler('module');
     $blockHandler =& xoops_gethandler('block');
     $t_objectArr =& $moduleHandler->getObjects();
     $successFlag = true;
     foreach ($t_objectArr as $module) {
         $mid = $module->get('mid');
         $olddata['name'] = $module->get('name');
         $olddata['weight'] = $module->get('weight');
         $olddata['isactive'] = $module->get('isactive');
         $newdata['name'] = $this->mActionForm->get('name', $mid);
         $newdata['weight'] = $this->mActionForm->get('weight', $mid);
         $newdata['isactive'] = $this->mActionForm->get('isactive', $mid);
         if (count(array_diff_assoc($olddata, $newdata)) > 0) {
             $module->set('name', $this->mActionForm->get('name', $mid));
             $module->set('weight', $this->mActionForm->get('weight', $mid));
             $module->set('isactive', $this->mActionForm->get('isactive', $mid));
             //
             // Store & Sync isactive of blocks with isactive of the module.
             //
             if ($moduleHandler->insert($module)) {
                 $successFlag &= true;
                 $blockHandler->syncIsActive($module->get('mid'), $module->get('isactive'));
             } else {
                 $successFlag = false;
             }
         }
     }
     return $successFlag ? LEGACY_FRAME_VIEW_SUCCESS : LEGACY_FRAME_VIEW_ERROR;
 }
Beispiel #7
0
 function treatPost()
 {
     $members = isset($_POST["lmembers"]) ? unserialize(base64_decode($_POST["lmembers"])) : null;
     $nonmemb = isset($_POST["lnonmemb"]) ? unserialize(base64_decode($_POST["lnonmemb"])) : null;
     $this->list = isset($_POST["list"]) ? unserialize(base64_decode($_POST["list"])) : null;
     if (!is_array($this->list)) {
         $this->loadList();
     }
     if (isset($_POST["bdeluser_x"])) {
         if (isset($_POST["members"])) {
             foreach ($_POST["members"] as $member) {
                 unset($members[$member]);
             }
         }
     } elseif (isset($_POST["badduser_x"])) {
         if (isset($_POST["nonmemb"])) {
             foreach ($_POST["nonmemb"] as $nm) {
                 $members[$nm] = $this->list[$nm];
             }
         }
     } elseif (isset($_POST["bconfirm"])) {
         header("Location: " . urlStrRedirect($this->set_order_uri, array('list' => base64_encode(serialize($this->list)))));
         exit;
     } else {
         $members = array();
         $nonmemb = $this->list;
     }
     ksort($members);
     reset($members);
     ksort($nonmemb);
     $this->diff = array_diff_assoc($nonmemb, $members);
     natcasesort($this->diff);
     $this->members = $members;
     $this->nonmemb = $nonmemb;
 }
 function actionDefault()
 {
     // Create the form
     $form = new YDForm('form1', 'GET', '', '_self', array('class' => 'myform'));
     // Add elements
     $form->addElement('text', 'txt1', 'Enter text 1:');
     $form->addElement('text', 'txt2', 'Enter text 2:');
     $form->addElement('submit', 'cmdSubmit', 'submit');
     $form->addRule('txt1', 'required', 'txt1 is required');
     $form->addRule('txt1', 'maxlength', 'txt1 must be smaller than 15', 15);
     $form->addCompareRule(array('txt1', 'txt2'), 'equal', 'txt1 and txt2 must be equal');
     $form->addFormRule('formrule1');
     $form->addFormRule(array('YDValidateRule', 'formrule2'));
     $form->addFilter('txt1', 'trim');
     $form->addFilter('txt2', 'trim');
     // Convert the form to XML
     $xml = $form->render('xml');
     YDDebugUtil::dump($xml, 'Form as XML data');
     //YDDebugUtil::dump( $form );
     // Recreate a new form from the XML data
     $form2 = new YDForm('form1');
     $form2->import('xml', $xml);
     //YDDebugUtil::dump( $form2 );
     YDDebugUtil::dump(array_diff_assoc($form->toArray(), $form2->toArray()), 'toArray difference');
     YDDebugUtil::dump(array_diff_assoc($form->_attributes, $form2->_attributes), '_attributes difference');
     YDDebugUtil::dump(array_diff_assoc($form->_elements, $form2->_elements), '_elements difference');
     YDDebugUtil::dump(array_diff_assoc($form->_rules, $form2->_rules), '_rules difference');
     YDDebugUtil::dump(array_diff_assoc($form->_filters, $form2->_filters), '_filters difference');
     YDDebugUtil::dump(array_diff_assoc($form->_comparerules, $form2->_comparerules), '_comparerules difference');
     YDDebugUtil::dump(array_diff_assoc($form->_formrules, $form2->_formrules), '_formrules difference');
     YDDebugUtil::dump(array_diff_assoc($form->_regElements, $form2->_regElements), '_regElements difference');
     YDDebugUtil::dump(array_diff_assoc($form->_regRules, $form2->_regRules), '_regRules difference');
     YDDebugUtil::dump(array_diff_assoc($form->_regFilters, $form2->_regFilters), '_regFilters difference');
     YDDebugUtil::dump(array_diff_assoc($form->_regRenderers, $form2->_regRenderers), '_regRenderers difference');
 }
Beispiel #9
0
 /**
  * Adds a signature to the request
  *
  * @access public
  * @author Joel Bout, <*****@*****.**>
  * @param $authorizationHeader Move the signature parameters into the Authorization header of the request
  */
 public function sign(common_http_Request $request, common_http_Credentials $credentials, $authorizationHeader = false)
 {
     if (!$credentials instanceof tao_models_classes_oauth_Credentials) {
         throw new tao_models_classes_oauth_Exception('Invalid credentals: ' . gettype($credentials));
     }
     $oauthRequest = $this->getOauthRequest($request);
     $dataStore = new tao_models_classes_oauth_DataStore();
     $consumer = $dataStore->getOauthConsumer($credentials);
     $token = $dataStore->new_request_token($consumer);
     $allInitialParameters = array();
     $allInitialParameters = array_merge($allInitialParameters, $request->getParams());
     $allInitialParameters = array_merge($allInitialParameters, $request->getHeaders());
     //oauth_body_hash is used for the signing computation
     if ($authorizationHeader) {
         $oauth_body_hash = base64_encode(sha1($request->getBody(), true));
         //the signature should be ciomputed from encoded versions
         $allInitialParameters = array_merge($allInitialParameters, array("oauth_body_hash" => $oauth_body_hash));
     }
     //$authorizationHeader = self::buildAuthorizationHeader($signatureParameters);
     $signedRequest = OAuthRequest::from_consumer_and_token($consumer, $token, $oauthRequest->get_normalized_http_method(), $oauthRequest->getUrl(), $allInitialParameters);
     $signature_method = new OAuthSignatureMethod_HMAC_SHA1();
     //common_logger::d('Base string: '.$signedRequest->get_signature_base_string());
     $signedRequest->sign_request($signature_method, $consumer, $token);
     common_logger::d('Base string from TAO/Joel: ' . $signedRequest->get_signature_base_string());
     if ($authorizationHeader) {
         $combinedParameters = $signedRequest->get_parameters();
         $signatureParameters = array_diff_assoc($combinedParameters, $allInitialParameters);
         $signatureParameters["oauth_body_hash"] = base64_encode(sha1($request->getBody(), true));
         $signatureHeaders = array("Authorization" => self::buildAuthorizationHeader($signatureParameters));
         $signedRequest = new common_http_Request($signedRequest->getUrl(), $signedRequest->get_normalized_http_method(), $request->getParams(), array_merge($signatureHeaders, $request->getHeaders()), $request->getBody());
     } else {
         $signedRequest = new common_http_Request($signedRequest->getUrl(), $signedRequest->get_normalized_http_method(), $signedRequest->get_parameters(), $request->getHeaders(), $request->getBody());
     }
     return $signedRequest;
 }
 /**
  * Compares two CSV files and determines for the transactions
  * the exact matches and subsequently closest matches for the ones not found in the other file
  * The process is repeated twice for the two files and the combined results are computed
  *
  * @param  String  $file1Path
  * @param  String  $file2Path
  * @return Array $comparisonResult
  */
 public static function compareFile($file1Path, $file2Path)
 {
     $file1 = self::csv_to_array($file1Path);
     $file2 = self::csv_to_array($file2Path);
     $matches = [];
     $non_matches = [];
     $count = 0;
     $countMatchReports = 0;
     for ($i = 0; $i < count($file1); ++$i) {
         $file1Transaction = $file1[$i];
         $matchFound = false;
         //Start searching from the current index of the first file, since the data is mostly ordered
         //in the files
         for ($j = $i; $j < count($file2); $j++) {
             $result = array_diff_assoc($file1Transaction, $file2[$j]);
             if (count($result) == 0) {
                 if (!isset($matches[$i])) {
                     $matches[$i] = $file1Transaction;
                 }
                 $matches[$i]['matched'] = 1;
                 $file2[$j]['matched'] = 1;
                 //$matches[$i]['matches'][] = $file2[$j];
                 $matchFound = true;
                 $countMatchReports++;
                 break;
             }
         }
         if (!$matchFound) {
             //Start searching from top of file up to last index we searched to or the full file
             //if the index has already exceeded the allowance
             $index = $i > count($file2) ? count($file2) : $i;
             for ($j = 0; $j < $index; $j++) {
                 $result = array_diff_assoc($file1Transaction, $file2[$j]);
                 if (count($result) == 0) {
                     if (!isset($matches[$i])) {
                         $matches[$i] = $file1Transaction;
                     }
                     $matches[$i]['matched'] = 1;
                     $file2[$j]['matched'] = 1;
                     //$matches[$i]['matches'][] = $file2[$j];
                     $matchFound = true;
                     $countMatchReports++;
                     break;
                 }
             }
         }
         if (!$matchFound) {
             $non_matches[$i + 2] = $file1Transaction;
         }
     }
     foreach ($non_matches as $key => $value) {
         $non_matches[$key] = self::findSuggestionForNonMatch($value, $file2);
     }
     $comparisonResult['TOTAL'] = count($file1);
     $comparisonResult['MATCHED'] = $countMatchReports;
     $comparisonResult['UNMATCHED_COUNT'] = count($non_matches);
     $comparisonResult['UNMATCHED_TRANSACTIIONS'] = $non_matches;
     //Try to find suggestions for transactions that did not match exactly
     return $comparisonResult;
 }
 /**
  * assert Sorted values
  *
  * @param array $array Sorted values array
  *
  * @return null
  */
 private function _assertSorted($array)
 {
     $copy = $array;
     sort($copy);
     $difference = array_diff_assoc($array, $copy);
     $this->assertEquals($difference, array());
 }
 /**
  * Validate given code using paramsArray
  * @param string $code
  * @param array $paramsArray
  * @return boolean
  */
 public function validate($code, $paramsArray = array())
 {
     if (empty($code)) {
         throw new InvalidArgumentException("Empty \$code supplied for validation!");
     }
     $this->query->exec("SELECT * FROM `" . Tbl::get('TBL_ONE_TIME_CODES') . "` WHERE `code`='{$code}' and (`valid_until` IS NULL OR `valid_until`>=NOW())");
     if ($this->query->countRecords() == 0) {
         return false;
     }
     $dbRow = $this->query->fetchRecord();
     $paramsArrayFromCode = $this->getArrayFromCode($dbRow['code']);
     if ($paramsArrayFromCode === false) {
         return false;
     }
     $resultingArray = array_diff_assoc($paramsArray, $paramsArrayFromCode);
     if (count($resultingArray) != 0) {
         return false;
     }
     if ($dbRow['multi'] == '1') {
         if ($dbRow['usage_limit'] > 0) {
             if ($dbRow['usage_count'] < $dbRow['usage_limit']) {
                 $this->query->exec("UPDATE `" . Tbl::get('TBL_ONE_TIME_CODES') . "` SET `usage_count`=`usage_count`+1 WHERE `id`='{$dbRow['id']}'");
             } else {
                 $this->query->exec("DELETE FROM `" . Tbl::get('TBL_ONE_TIME_CODES') . "` WHERE `id`='{$dbRow['id']}'");
                 return false;
             }
         }
     } else {
         $this->query->exec("DELETE FROM `" . Tbl::get('TBL_ONE_TIME_CODES') . "` WHERE `id`='{$dbRow['id']}'");
     }
     return true;
 }
 /**
  * Is the data set valid?
  *
  * @return bool
  */
 public function isValid()
 {
     $isValid = parent::isValid();
     foreach ($this->getUniqueFields() as $uniqueField) {
         $validatedValues = array();
         foreach ($this->collectionData as $key => $values) {
             if (!is_array($values)) {
                 $values = array();
             }
             if (array_key_exists($uniqueField, $values)) {
                 $validatedValues[$key] = $values[$uniqueField];
             }
         }
         unset($key);
         $uniqueValues = array_values(array_unique($validatedValues, SORT_REGULAR));
         if (count($uniqueValues) < count($validatedValues)) {
             $isValid = false;
             $notUnique = array_keys(array_diff_assoc($validatedValues, $uniqueValues));
             foreach ($notUnique as $key) {
                 $this->collectionMessages[$key][$uniqueField][self::NOT_UNIQUE] = $this->messageTemplates[self::NOT_UNIQUE];
             }
         }
     }
     return $isValid;
 }
Beispiel #14
0
function getRelPath3($a, $b)
{
    $a = explode('/', $a);
    $b = explode('/', $b);
    $diff = array_diff_assoc($a, $b);
    return implode('/', array_slice($a, key($diff)));
}
Beispiel #15
0
 protected function validate_settings()
 {
     if (!$this->can_save()) {
         return;
     }
     $previous_settings = ITSEC_Modules::get_settings($this->get_id());
     $diff = array_diff_assoc($this->settings, $previous_settings);
     if (!empty($diff)) {
         ITSEC_Response::regenerate_server_config();
     }
     if ($this->settings['write_permissions']) {
         // Always set permissions to 0444 when saving the settings.
         // This ensures that the file permissions are fixed each time the settings are saved.
         $new_permissions = 0444;
     } else {
         if ($this->settings['write_permissions'] !== $previous_settings['write_permissions']) {
             // Only revert the settings to the defaults when disabling the setting.
             // This avoids changing the file permissions when the setting has yet to be enabled and disabled.
             $new_permissions = 0664;
         }
     }
     if (isset($new_permissions)) {
         // Only change the permissions when needed.
         require_once ITSEC_Core::get_core_dir() . 'lib/class-itsec-lib-config-file.php';
         require_once ITSEC_Core::get_core_dir() . 'lib/class-itsec-lib-file.php';
         $server_config_file = ITSEC_Lib_Config_File::get_server_config_file_path();
         $wp_config_file = ITSEC_Lib_Config_File::get_wp_config_file_path();
         ITSEC_Lib_File::chmod($server_config_file, $new_permissions);
         ITSEC_Lib_File::chmod($wp_config_file, $new_permissions);
         ITSEC_Response::reload_module('file-permissions');
     }
 }
 /**
  * @dataProvider pluginActionProvider
  * @param array<string> $old_actions
  */
 public function testFilterPluginActions(array $old_actions)
 {
     $settings = $this->createMock();
     $new_actions = $settings->filterPluginActions($old_actions, 'pfadfinden-theme-updater/pfadfinden-theme-updater.php', array(), 'All');
     $this->assertCount(1, array_diff_assoc($new_actions, $old_actions), 'Our action gets added.');
     $this->assertCount(0, array_diff_assoc($old_actions, $new_actions), 'No actions are removed.');
 }
 public function product_template_isset($template_name = '', $attribute_value_id = array(), $category_id = 0)
 {
     //找出规格数组中需要的数据
     $attribute = array();
     foreach ($attribute_value_id as $key => $value) {
         $attribute[] = $value['attribute_id'];
     }
     //对数组中的编号进行排序
     sort($attribute);
     //查找是否存在该产品模版
     $search_product_template_id = $this->exe_rpc_call('product.template', 'search_read', array(array(array("name", "=", "{$template_name}"), array("categ_id", "=", $category_id))));
     //遍历每一个符合相同父类路径下面的相同名字的模版
     foreach ($search_product_template_id as $key => $value) {
         //找出每一个模版下面的属性
         $product_attribute_line = $this->exe_rpc_call('product.attribute.line', 'search_read', array(array(array("product_tmpl_id", "=", $value['id']))));
         //每一个符合条件的模版下面的所有属性编号
         $attribute_line = array();
         foreach ($product_attribute_line as $line_key => $line_value) {
             $attribute_line[] = $line_value['attribute_id'][0];
         }
         //对符合条件的模版下面的属性编号排序
         sort($attribute_line);
         //如果当前模版的属性编号和传进来的属性编号进行比较,如果返回值为空,则证明存在该产品模版
         if (count($attribute_line) == count($attribute) && empty(array_diff_assoc($attribute_line, $attribute))) {
             return $value['id'];
         }
     }
     return false;
 }
 private function annotationRoute()
 {
     $this->routeConfFile = $this->projectsFolder . DIRECTORY_SEPARATOR . self::ROUTER_CONFIG_PATH;
     $fh = fopen($this->routeConfFile, 'r');
     $routeAnnotationsString = fgets($fh);
     fclose($fh);
     $annotations = explode("@#@", $routeAnnotationsString);
     foreach ($annotations as $annotation) {
         if ($annotation == "") {
             continue;
         }
         $annotationArr = explode(" ", $annotation);
         $controllerNameSpaceAnno = array_shift($annotationArr);
         $controllerNameAnno = array_shift($annotationArr);
         $actionNameAnno = array_shift($annotationArr);
         $an = $annotationArr[0];
         preg_match_all("/\\(([^}]*)\\)/", $an, $annotationPath);
         $annotationPathArr = explode("/", $annotationPath[1][0]);
         $diffArr = array_diff_assoc($this->requestParams, $annotationPathArr);
         //var_dump($diffArr);
         if (!$diffArr) {
             //var_dump($controllerNameSpaceAnno, $controllerNameAnno, $actionNameAnno);
             $this->controllerNameSpace = $controllerNameSpaceAnno;
             $this->controller = $controllerNameAnno;
             $this->action = $actionNameAnno;
             return true;
         }
     }
     return false;
 }
 public function attributes()
 {
     $attributes = array('id' => $this->id, 'class' => $this->definition->getClass(), 'scope' => $this->definition->getScope(), 'public' => $this->definition->isPublic(), 'synthetic' => $this->definition->isSynthetic(), 'synchronized' => $this->definition->isSynchronized(), 'lazy' => $this->definition->isLazy(), 'abstract' => $this->definition->isAbstract(), 'factory-class' => $this->definition->getFactoryClass(), 'factory-method' => $this->definition->getFactoryMethod(), 'factory-service' => $this->definition->getFactoryService());
     $defaults = array('id' => null, 'class' => null, 'scope' => 'container', 'public' => true, 'synthetic' => false, 'synchronized' => false, 'lazy' => false, 'abstract' => false, 'factory-class' => null, 'factory-method' => null, 'factory-service' => null);
     $diff = array_diff_assoc($attributes, $defaults);
     return new ArrayAttributes($diff);
 }
Beispiel #20
0
 /**
  * Parses HTML and extracts meta tags
  *
  * @param $HTML    HTML to parse
  * @return MetaData
  */
 private static function _parse($HTML)
 {
     $page = new self();
     $rawTags = array();
     preg_match_all("|<meta[^>]+=\"([^\"]*)\"[^>]" . "+content=\"([^\"]*)\"[^>]+>|i", $HTML, $rawTags, PREG_PATTERN_ORDER);
     if (!empty($rawTags)) {
         $multiValueTags = array_unique(array_diff_assoc($rawTags[1], array_unique($rawTags[1])));
         for ($i = 0; $i < sizeof($rawTags[1]); $i++) {
             $hasMultiValues = false;
             $tag = $rawTags[1][$i];
             foreach ($multiValueTags as $mTag) {
                 if ($tag == $mTag) {
                     $hasMultiValues = true;
                 }
             }
             if ($hasMultiValues) {
                 $page->_values[$tag][] = $rawTags[2][$i];
             } else {
                 $page->_values[$tag] = $rawTags[2][$i];
             }
         }
     }
     if (empty($page->_values)) {
         return false;
     }
     return $page;
 }
Beispiel #21
0
 /**
  * @return boolean|quipThread
  */
 public function getThread()
 {
     $threadName = $this->getProperty('thread', '');
     if (empty($threadName)) {
         return false;
     }
     $this->thread = $this->modx->getObject('quipThread', array('name' => $threadName));
     if (empty($this->thread)) {
         $this->thread = $this->modx->newObject('quipThread');
         $this->thread->fromArray(array('name' => $threadName, 'createdon' => strftime('%Y-%m-%d %H:%M:%S', time()), 'moderated' => $this->getProperty('moderate', 0, 'isset'), 'resource' => $this->modx->resource->get('id'), 'idprefix' => $this->getProperty('idprefix', 'qcom')), '', true, true);
         $this->thread->save();
     }
     /* sync properties with thread row values */
     $this->thread->sync($this->getProperties());
     $ps = $this->thread->get('quipreply_call_params');
     if (!empty($ps)) {
         $diff = array_diff_assoc($ps, $this->getProperties());
         if (empty($diff)) {
             $diff = array_diff_assoc($this->getProperties(), $ps);
         }
     }
     if (empty($_REQUEST['quip_thread']) && (!empty($diff) || empty($ps))) {
         /* only sync call params if not on threaded reply page */
         $this->thread->set('quipreply_call_params', $this->getProperties());
         $this->thread->save();
     }
     /* if in threaded reply page, get the original passing values to QuipReply in the thread's main page and use those */
     if (!empty($_REQUEST['quip_thread']) && is_array($ps) && !empty($ps)) {
         $scriptProperties = array_merge($this->getProperties(), $ps);
         $this->setProperties($scriptProperties);
     }
     unset($ps, $diff);
     return $this->thread;
 }
Beispiel #22
0
 public function updateInstall(Install $originalInstall, Install $newInstall)
 {
     $fields = array_diff_assoc($newInstall->dump(), $originalInstall->dump());
     $fields['id'] = $originalInstall->getId();
     $query = sprintf(static::UPDATE_PATCH, $this->buildSet($fields));
     $this->query->write($query, $fields);
 }
    /**
     * @param YoPdo $yo_pdo
     * @param string $table_name
     * @param array $expected_results
     * @return array
     */
    public function assertResults(YoPdo $yo_pdo, $table_name, array $expected_results)
    {
        $column_sql = '';
        if ($expected_results && reset($expected_results)) {
            $column_sql = ', ' . implode(', ', array_keys(reset($expected_results)));
        }
        $sql = <<<SQL
SELECT id {$column_sql}
FROM {$table_name}
ORDER BY id
SQL;
        $result = $yo_pdo->query($sql);
        while ($row = $result->fetch()) {
            if (!array_key_exists('id', $row)) {
                $this->test_case->assertTrue(false, "Field 'id' not found in row.");
            } elseif (!array_key_exists($row['id'], $expected_results)) {
                $this->test_case->assertTrue(false, "Row with key '{$row['id']}' not found in expected results.");
            } else {
                $expected_result = $expected_results[$row['id']];
                $expected_result['id'] = $row['id'];
                if (array_diff_assoc($expected_result, $row) || array_diff_assoc($row, $expected_result)) {
                    $this->test_case->assertEquals($expected_result, $row);
                }
                unset($expected_results[$row['id']]);
            }
        }
        $this->test_case->assertEmpty($expected_results);
    }
Beispiel #24
0
 public function updatePatch(Patch $originalPatch, Patch $newPatch)
 {
     $fields = array_diff_assoc($originalPatch->dump(), $newPatch->dump());
     $fields['id'] = $originalPatch->getId();
     $query = sprintf(static::UPDATE_PATCH, $this->buildSet($fields));
     $this->query->write($query, $fields);
 }
 public function testCanSendNormalRequest()
 {
     $this->streamMock->shouldReceive('streamContextCreate')->once()->with(m::on(function ($arg) {
         if (!isset($arg['http']) || !isset($arg['ssl'])) {
             return false;
         }
         if ($arg['http'] !== ['method' => 'GET', 'timeout' => 60, 'ignore_errors' => true, 'header' => 'X-foo: bar']) {
             return false;
         }
         $caInfo = array_diff_assoc($arg['ssl'], ['verify_peer' => true, 'verify_peer_name' => true, 'allow_self_signed' => true]);
         if (count($caInfo) !== 1) {
             return false;
         }
         if (1 !== preg_match('/.+\\/certs\\/DigiCertHighAssuranceEVRootCA\\.pem$/', $caInfo['cafile'])) {
             return false;
         }
         return true;
     }))->andReturn(null);
     $this->streamMock->shouldReceive('getResponseHeaders')->once()->andReturn(explode("\n", trim($this->fakeRawHeader)));
     $this->streamMock->shouldReceive('fileGetContents')->once()->with('http://foo.com/')->andReturn($this->fakeRawBody);
     $this->streamClient->addRequestHeader('X-foo', 'bar');
     $responseBody = $this->streamClient->send('http://foo.com/');
     $this->assertEquals($responseBody, $this->fakeRawBody);
     $this->assertEquals($this->streamClient->getResponseHeaders(), $this->fakeHeadersAsArray);
     $this->assertEquals(200, $this->streamClient->getResponseHttpStatusCode());
 }
 /**
  * Verify data in form equals to passed from fixture
  *
  * @param array $dataFixture
  * @param array $dataForm
  * @return array
  */
 protected function verify(array $dataFixture, array $dataForm)
 {
     $result = [];
     $customerDiff = array_diff_assoc($dataFixture['customer'], $dataForm['customer']);
     foreach ($customerDiff as $name => $value) {
         if (in_array($name, $this->customerSkippedFields)) {
             continue;
         }
         if (isset($dataForm['customer'][$name])) {
             $result[] = "\ncustomer {$name}: \"{$dataForm['customer'][$name]}\" instead of \"{$value}\"";
         } else {
             $result[] = "\ncustomer {$name}: Field is absent. Expected value \"{$value}\"";
         }
     }
     foreach ($dataFixture['addresses'] as $key => $address) {
         $addressDiff = array_diff($address, $dataForm['addresses'][$key]);
         foreach ($addressDiff as $name => $value) {
             if (isset($dataForm['addresses'][$key][$name])) {
                 $result[] = "\naddress #{$key} {$name}: \"{$dataForm['addresses'][$key][$name]}" . "\" instead of \"{$value}\"";
             } else {
                 $result[] = "\naddress #{$key} {$name}: Field absent. Expected value \"{$value}\"";
             }
         }
     }
     return $result;
 }
 /**
  * Extract current session page
  *
  * @param string $root_path current root path (phpbb_root_path)
  */
 function extract_current_page($root_path)
 {
     $page_array = array();
     // First of all, get the request uri...
     $script_name = !empty($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : getenv('PHP_SELF');
     $args = !empty($_SERVER['QUERY_STRING']) ? explode('&', $_SERVER['QUERY_STRING']) : explode('&', getenv('QUERY_STRING'));
     // If we are unable to get the script name we use REQUEST_URI as a failover and note it within the page array for easier support...
     if (!$script_name) {
         $script_name = !empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : getenv('REQUEST_URI');
         $script_name = ($pos = strpos($script_name, '?')) !== false ? substr($script_name, 0, $pos) : $script_name;
         $page_array['failover'] = 1;
     }
     // Replace backslashes and doubled slashes (could happen on some proxy setups)
     $script_name = str_replace(array('\\', '//'), '/', $script_name);
     // Now, remove the sid and let us get a clean query string...
     $use_args = array();
     // Since some browser do not encode correctly we need to do this with some "special" characters...
     // " -> %22, ' => %27, < -> %3C, > -> %3E
     $find = array('"', "'", '<', '>');
     $replace = array('%22', '%27', '%3C', '%3E');
     foreach ($args as $key => $argument) {
         if (strpos($argument, 'sid=') === 0) {
             continue;
         }
         $use_args[] = str_replace($find, $replace, $argument);
     }
     unset($args);
     // The following examples given are for an request uri of {path to the phpbb directory}/adm/index.php?i=10&b=2
     // The current query string
     $query_string = trim(implode('&', $use_args));
     // basenamed page name (for example: index.php)
     $page_name = substr($script_name, -1, 1) == '/' ? '' : basename($script_name);
     $page_name = urlencode(htmlspecialchars($page_name));
     // current directory within the phpBB root (for example: adm)
     $root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($root_path)));
     $page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath('./')));
     $intersection = array_intersect_assoc($root_dirs, $page_dirs);
     $root_dirs = array_diff_assoc($root_dirs, $intersection);
     $page_dirs = array_diff_assoc($page_dirs, $intersection);
     $page_dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);
     if ($page_dir && substr($page_dir, -1, 1) == '/') {
         $page_dir = substr($page_dir, 0, -1);
     }
     // Current page from phpBB root (for example: adm/index.php?i=10&b=2)
     $page = ($page_dir ? $page_dir . '/' : '') . $page_name . ($query_string ? "?{$query_string}" : '');
     // The script path from the webroot to the current directory (for example: /phpBB3/adm/) : always prefixed with / and ends in /
     $script_path = trim(str_replace('\\', '/', dirname($script_name)));
     // The script path from the webroot to the phpBB root (for example: /phpBB3/)
     $script_dirs = explode('/', $script_path);
     array_splice($script_dirs, -sizeof($page_dirs));
     $root_script_path = implode('/', $script_dirs) . (sizeof($root_dirs) ? '/' . implode('/', $root_dirs) : '');
     // We are on the base level (phpBB root == webroot), lets adjust the variables a bit...
     if (!$root_script_path) {
         $root_script_path = $page_dir ? str_replace($page_dir, '', $script_path) : $script_path;
     }
     $script_path .= substr($script_path, -1, 1) == '/' ? '' : '/';
     $root_script_path .= substr($root_script_path, -1, 1) == '/' ? '' : '/';
     $page_array += array('page_name' => $page_name, 'page_dir' => $page_dir, 'query_string' => $query_string, 'script_path' => str_replace(' ', '%20', htmlspecialchars($script_path)), 'root_script_path' => str_replace(' ', '%20', htmlspecialchars($root_script_path)), 'page' => $page, 'forum' => isset($_REQUEST['f']) && $_REQUEST['f'] > 0 ? (int) $_REQUEST['f'] : 0);
     return $page_array;
 }
Beispiel #28
0
 /**
  * constuctor
  */
 function rss_forum(&$gym_master)
 {
     global $user, $db;
     $this->gym_master =& $gym_master;
     $this->actions =& $this->gym_master->actions;
     $this->module_auth =& $this->gym_master->module_auth;
     $this->output_data =& $this->gym_master->output_data;
     $this->module_config =& $this->gym_master->rss_config;
     $this->url_config =& $this->gym_master->url_config;
     $this->module_config = array_merge($this->module_config, array('rss_first' => $this->gym_master->gym_config['rss_forum_first'] ? TRUE : FALSE, 'rss_last' => $this->gym_master->gym_config['rss_forum_last'] ? TRUE : FALSE, 'rss_forum_rules' => $this->gym_master->gym_config['rss_forum_rules'] ? TRUE : FALSE, 'rss_exclude_list' => trim($this->gym_master->gym_config['rss_forum_exclude'], ',')));
     // Set up msg outpout
     if ($this->actions['rss_news_list'] || $this->actions['module_sub'] === 'announces') {
         $this->module_config['rss_first'] = true;
         $this->module_config['rss_last'] = false;
         $this->module_config['rss_sort'] = 'DESC';
     } else {
         $this->module_config['rss_last'] = $this->module_config['rss_first'] ? $this->module_config['rss_last'] : true;
     }
     // Build unauthed array
     $this->module_config['exclude_list'] = $this->gym_master->set_exclude_list($this->module_config['rss_exclude_list']);
     // Wee need to check auth here
     $this->gym_master->check_forum_auth($this->module_config['rss_auth_guest']);
     $this->actions['auth_guest_read'] = array_diff_assoc($this->module_auth['forum']['public_read'], $this->module_config['exclude_list'], $this->module_auth['forum']['skip_all']);
     $this->actions['auth_view_read'] = array_diff_assoc($this->module_auth['forum']['read_post'], $this->module_config['exclude_list']);
     if (empty($this->actions['auth_view_read'])) {
         $this->gym_master->gym_error(404, '', __FILE__, __LINE__);
     }
     $this->actions['in_id_sql'] = $db->sql_in_set('forum_id', $this->actions['auth_view_read'], false, true);
     $this->gym_master->gym_output->setup_cache();
     // Will exit if the cache is sent
     $this->init_url_settings();
 }
 public function edit(Request $request)
 {
     if (!\Session::get('user')->can('服务器信息管理')) {
         abort(401);
     }
     $server = Server::find($request->input('id'));
     $old_attributes = $server->attributesToArray();
     $server->name = $request->input('name');
     $server->provider = $request->input('provider');
     $server->barcode = $request->input('barcode');
     $server->sn = $request->input('sn');
     $server->model = $request->input('model');
     $server->cpu = $request->input('cpu');
     $server->memory = $request->input('memory');
     $server->disk = $request->input('disk');
     $server->os = $request->input('os');
     $server->fqdn = $request->input('fqdn');
     $server->vpn = $request->input('vpn');
     $server->description = $request->input('description');
     $server->inner_ip = $request->input('inner_ip');
     $server->outer_ip = $request->input('outer_ip');
     $new_attributes = $server->attributesToArray();
     $user = \Session::get('user');
     foreach (array_diff_assoc($old_attributes, $new_attributes) as $key => $value) {
         \Log::notice(strtr('服务器修改: 用户(%name[%id]) 修改了服务器 (%server[%server_id]) 的基本信息: [%key] %old --> %new', ['%name' => $user->name, '%id' => $user->id, '%server' => $server->name, '%server_id' => $server->id, '%key' => $key, '%old' => $old_attributes[$key], '%new' => $new_attributes[$key]]));
     }
     if ($server->save()) {
         return redirect()->to(route('server.profile', ['id' => $server->id]))->with('message_content', '修改成功!')->with('message_type', 'info');
     }
 }
 /**
  * {@inheritDoc}
  */
 public function setOptions(array $options = array(), $force = false)
 {
     if (false === $force && !($diff = array_diff_assoc($options, $this->options))) {
         return;
     }
     $defaultOptions = $this->getDefaultOptions();
     // check option names
     if ($diff = array_diff(array_keys($options), array_keys($defaultOptions))) {
         throw new \InvalidArgumentException(sprintf('The YUIJavascriptCompressor does not support the following options: \'%s\'.', implode('\', \'', $diff)));
     }
     $this->options = array_merge($defaultOptions, $options);
     // check vendor path
     if (false === is_file($this->options['path'])) {
         throw new \InvalidArgumentException(sprintf('The path of the yui-compressor not found (%s)', $this->options['path']));
     }
     $this->executable = 'java -jar ' . $this->options['path'];
     $this->commandOptions = array('--type js', sprintf('--charset %s', $this->options['charset']), sprintf('--line-break %d', $this->options['line_break']));
     if ($this->options['munge'] === false) {
         $this->commandOptions[] = '--nomunge';
     }
     if ($this->options['optimize'] === false) {
         $this->commandOptions[] = '--disable-optimizations';
     }
     if ($this->options['preserve_semicolons'] === true) {
         $this->commandOptions[] = '--preserve-semi';
     }
 }