/** * Short description of method intersect * * @access public * @author Jerome Bogaerts, <*****@*****.**> * @param Collection collection * @return core_kernel_classes_ContainerCollection */ public function intersect(common_Collection $collection) { $returnValue = null; $returnValue = new core_kernel_classes_ContainerCollection(new common_Object(__METHOD__)); $returnValue->sequence = array_uintersect($this->sequence, $collection->sequence, 'core_kernel_classes_ContainerComparator::compare'); return $returnValue; }
public function execute(array $collection) { $comparer = $this->getComparer(); return array_values(array_uintersect($collection, $this->collectionToIntersect, function ($a, $b) use($comparer) { return $comparer->equals($a, $b); })); }
/** * 获取版块列表 */ public function listAction() { /* @var $daoBoard Dao_Td_Board_Board */ $daoBoard = Tudu_Dao_Manager::getDao('Dao_Td_Board_Board', Tudu_Dao_Manager::DB_TS); $boards = $daoBoard->getBoards(array('orgid' => $this->_user->orgId, 'uniqueid' => $this->_user->uniqueId))->toArray('boardid'); $return = array(); foreach ($boards as $bid => $board) { if ($board['issystem'] || $board['status'] != 0) { continue; } if ($board['parentid']) { if (!array_key_exists($bid, $boards)) { continue; } if (!in_array('^all', $board['groups']) && !(in_array($this->_user->userName, $board['groups'], true) || in_array($this->_user->address, $board['groups'], true)) && !sizeof(array_uintersect($this->_user->groups, $board['groups'], "strcasecmp")) && !array_key_exists($this->_user->userId, $board['moderators']) && !($board['ownerid'] == $this->_user->userId) && !array_key_exists($this->_user->userId, $boards[$board['parentid']]['moderators'])) { continue; } $boards[$board['parentid']]['children'][] =& $boards[$bid]; } else { $return[] =& $boards[$bid]; } } $ret = array(); foreach ($return as $item) { if (empty($item['children'])) { continue; } $ret[] = array('orgid' => $item['orgid'], 'boardid' => $item['boardid'], 'type' => $item['type'], 'boardname' => $item['boardname'], 'privacy' => (int) $item['privacy'], 'ordernum' => (int) $item['ordernum'], 'issystem' => (int) $item['issystem'], 'needconfirm' => (int) $item['needconfirm'], 'isflowonly' => (int) $item['flowonly'], 'isclassify' => (int) $item['isclassify'], 'status' => (int) $item['status'], 'children' => $this->_formatBoardChildren($item['children']), 'updatetime' => null); } $this->view->code = TuduX_OpenApi_ResponseCode::SUCCESS; $this->view->boards = $ret; }
/** * Parses the search text to a query wich will search in each of the specified fields. * If operators AND, OR or NOT are used in the text it is considered search text query and is passed as it is. * If it is a simple text - it is escaped and truncated. * * @param string $searchText * @param array $fields * @param string $truncate */ public function parse($searchText, $truncate, $fields) { $nonTokenizedFields = array_uintersect($fields, self::$_nonTokenizedFields, array('OpenSKOS_Solr_Queryparser_Editor_ParseSearchText', 'compareMultiLangFields')); $fields = array_udiff($fields, self::$_nonTokenizedFields, array('OpenSKOS_Solr_Queryparser_Editor_ParseSearchText', 'compareMultiLangFields')); $simpleFieldsQuery = ''; $normalFieldsQuery = ''; if ($this->_isSearchTextQuery($searchText)) { $simpleFieldsQuery = $this->_buildQueryForSearchTextInFields('(' . $searchText . ')', $nonTokenizedFields); $normalFieldsQuery = $this->_buildQueryForSearchTextInFields('(' . $searchText . ')', $fields); } else { $trimedSearchText = trim($searchText); if (empty($trimedSearchText)) { $searchText = '*'; } $searchTextForNonTokenized = $this->_escapeSpecialChars($searchText); $simpleFieldsQuery = $this->_buildQueryForSearchTextInFields('(' . $searchTextForNonTokenized . ')', $nonTokenizedFields); $searchTextForTokenized = $this->_replaceTokenizeDelimiterChars($searchText); $normalFieldsQuery = $this->_buildQueryForSearchTextInFields('(' . $searchTextForTokenized . ')', $fields); } if ($simpleFieldsQuery != '' && $normalFieldsQuery != '') { return $simpleFieldsQuery . ' OR ' . $normalFieldsQuery; } else { return $simpleFieldsQuery . $normalFieldsQuery; } }
/** * @param \Generated\Shared\Transfer\QuoteTransfer $quoteTransfer * * @return \Generated\Shared\Transfer\DiscountableItemTransfer[] */ public function collect(QuoteTransfer $quoteTransfer) { $lefCollectedItems = $this->left->collect($quoteTransfer); $rightCollectedItems = $this->right->collect($quoteTransfer); return array_uintersect($lefCollectedItems, $rightCollectedItems, function (DiscountableItemTransfer $collected, DiscountableItemTransfer $toCollect) { return strcmp(spl_object_hash($collected->getOriginalItemCalculatedDiscounts()), spl_object_hash($toCollect->getOriginalItemCalculatedDiscounts())); }); }
public function filterArray(&$array, $children = false) { if ($children === false) { $children = $this->children; } $count = count($children); if ($count === 1) { $children[0]->filterArray($array); } else { $processedArray = array(); $opArray = array(); //Process parens first $parens = array(); for ($i = 0; $i < $count; $i++) { if (!isset($children[$i])) { continue; } if ($children[$i] === '(') { unset($children[$i]); for ($j = $i + 1; $j < $count; $j++) { if ($children[$j] === ')') { unset($children[$j]); break; } array_push($parens, $children[$j]); unset($children[$j]); } $index = array_push($processedArray, $array); $this->filterArray($processedArray[$index - 1], $parens); $parens = null; } } for ($i = 0; $i < $count; $i++) { if (!isset($children[$i])) { continue; } if (is_object($children[$i])) { $index = array_push($processedArray, $array); $children[$i]->filterArray($processedArray[$index - 1]); } else { array_push($opArray, $children[$i]); } } $i = 1; foreach ($opArray as $op) { if ($op === 'and') { $tmp = array_uintersect($processedArray[0], $processedArray[$i], array($this, 'compareAll')); $processedArray[0] = $tmp; $i++; } else { throw new Exception('Not handling or yet!'); } } $array = $processedArray[0]; } }
function test($a1, $a2, $k) { $res = array_uintersect($a1, $a2, function ($i, $j) use($k) { if ($i[$k] == $j[$k]) { return 0; } return -1; }); return $res; }
public function dbmsSelector($name = 'dbType', $default = NULL) { $availableDrivers = Doctrine_Manager::getInstance()->getCurrentConnection()->getAvailableDrivers(); $supportedDrivers = Doctrine_Manager::getInstance()->getCurrentConnection()->getSupportedDrivers(); $drivers = array_uintersect($availableDrivers, $supportedDrivers, 'strcasecmp'); foreach ($drivers as $driver) { $driversPDO[$driver] = $driver; } $dbTypes = $driversPDO; return form::dropdown($name, $dbTypes, $default); }
/** * Возвращает элементы изменившиеся с последнего обновления * @param Array $newArray новые данные * @param Array $originArray текущие данные * @return Array */ public static function itemsForUpdate(array $newArray, array $originArray) { return array_uintersect($newArray, $originArray, function ($a, $b) { if ($a['id'] < $b['id']) { return -1; } elseif ($a['id'] > $b['id']) { return 1; } else { if ($a != $b) { return 0; } else { return 1; } } }); }
/** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $integration_object = $options['integration_object']; //add custom feature settings $integration_object->appendToForm($builder, $options['data'], 'features'); $leadFields = $options['lead_fields']; $formModifier = function (FormInterface $form, $data, $method = 'get') use($integration_object, $leadFields) { $settings = ['silence_exceptions' => false, 'feature_settings' => $data]; try { $fields = $integration_object->getFormLeadFields($settings); if (!is_array($fields)) { $fields = []; } $error = ''; } catch (\Exception $e) { $fields = []; $error = $e->getMessage(); } list($specialInstructions, $alertType) = $integration_object->getFormNotes('leadfield_match'); /** * Auto Match Integration Fields with Mautic Fields. */ $flattenLeadFields = []; foreach (array_values($leadFields) as $fieldsWithoutGroups) { $flattenLeadFields = array_merge($flattenLeadFields, $fieldsWithoutGroups); } $integrationFields = array_keys($fields); $flattenLeadFields = array_keys($flattenLeadFields); $fieldsIntersection = array_uintersect($integrationFields, $flattenLeadFields, 'strcasecmp'); $autoMatchedFields = []; foreach ($fieldsIntersection as $field) { $autoMatchedFields[$field] = strtolower($field); } $form->add('leadFields', 'integration_fields', ['label' => 'mautic.integration.leadfield_matches', 'required' => true, 'lead_fields' => $leadFields, 'data' => isset($data['leadFields']) && !empty($data['leadFields']) ? $data['leadFields'] : $autoMatchedFields, 'integration_fields' => $fields, 'special_instructions' => $specialInstructions, 'alert_type' => $alertType]); if ($method == 'get' && $error) { $form->addError(new FormError($error)); } }; $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use($formModifier) { $data = $event->getData(); $formModifier($event->getForm(), $data); }); $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use($formModifier) { $data = $event->getData(); $formModifier($event->getForm(), $data, 'post'); }); }
public function relatedCargo() { $from_radius = (int) $this->from_radius; $radius_from = ($from_radius < 25 ? 25 : $from_radius) / 111.144; $lat_from = (double) $this->from_address_lat; $lng_from = (double) $this->from_address_long; $conditionFrom = "((a.lat BETWEEN '" . ($lat_from - $radius_from) . "' AND '" . ($lat_from + $radius_from) . "') \r\n AND (a.`long` BETWEEN '" . ($lng_from - $radius_from) . "' AND '" . ($lng_from + $radius_from) . "')\r\n AND (SQRT(POW(" . $lat_from . "-a.lat,2)+POW(" . $lng_from . "-a.`long`,2)) <" . $radius_from . ") AND a.direction='from')"; $cargoIdFrom = Yii::app()->db->createCommand()->select('ra.cargo_id')->from('site_cargo_address ra')->leftJoin('site_address a', 'a.address_id=ra.address_id')->where($conditionFrom)->queryColumn(); $to_radius = (int) $this->to_radius; $radius_to = ($to_radius < 25 ? 25 : $to_radius) / 111.144; $lat_to = (double) $this->to_address_lat; $lng_to = (double) $this->to_address_long; $conditionTo = "((a.lat BETWEEN '" . ($lat_to - $radius_to) . "' AND '" . ($lat_to + $radius_to) . "') \r\n AND (a.`long` BETWEEN '" . ($lng_to - $radius_to) . "' AND '" . ($lng_to + $radius_to) . "')\r\n AND (SQRT(POW(" . $lat_to . "-a.lat,2)+POW(" . $lng_to . "-a.`long`,2)) <" . $radius_to . ") AND a.direction='to')"; $cargoIdTo = Yii::app()->db->createCommand()->select('ra.cargo_id')->from('site_cargo_address ra')->leftJoin('site_address a', 'a.address_id=ra.address_id')->where($conditionTo)->queryColumn(); $cargoIds = array_uintersect($cargoIdFrom, $cargoIdTo, "strcasecmp"); return $cargoIds; }
/** * @see Editor_Models_ConceptValidator::validate($concept) */ public function isValid(Editor_Models_Concept $concept, $extraData) { $this->_setField('broader'); $isValid = true; $allBroaders = $concept->getRelationsByField('broader', null, array($concept, 'getAllRelations')); $allNarrowers = $concept->getRelationsByField('narrower', null, array($concept, 'getAllRelations')); $matches = array_uintersect($allBroaders, $allNarrowers, array('Api_Models_Concept', 'compare')); if (!empty($matches)) { $isValid = false; foreach ($matches as $broader) { $broader = new Editor_Models_Concept($broader); $this->_addConflictedConcept($broader); } } if (!$isValid) { $this->_setErrorMessage(_('One or more of the broader relations create a cycle')); } return $isValid; }
/** * @param $tableName * @param $columns * @param @CsvFile[] $sourceData */ public function import($tableName, $columns, array $sourceData, array $options = []) { $this->importedRowsCount = 0; $this->importedColumns = 0; $this->warnings = []; $this->timers = []; $this->validate($tableName, $columns); $stagingTableName = $this->createStagingTable($tableName, $this->getIncremental()); foreach ($sourceData as $csvFile) { $this->importTableColumnsAll($stagingTableName, $columns, $csvFile); } if ($this->getIncremental()) { $importColumns = array_uintersect($this->tableColumns($tableName), $columns, 'strcasecmp'); $this->insertOrUpdateTargetTable($stagingTableName, $tableName, $importColumns); } else { $this->swapTables($stagingTableName, $tableName); } $this->dropTable($stagingTableName, $this->getIncremental()); return new Result(['warnings' => $this->warnings, 'timers' => $this->timers, 'importedRowsCount' => $this->importedRowsCount, 'importedColumns' => $this->importedColumns]); }
/** * Get components to be added. * * @return array */ protected function getComponentsToRegister() { static $components = null; if (!is_null($components)) { return $components; } $mode = Settings::get('mode', 'all'); $componentsTmp = []; if ($mode == 'allBut') { $componentsTmp = array_udiff($this->componentList, $this->getSettingsList(), 'strcasecmp'); } elseif ($mode == 'only') { $componentsTmp = array_uintersect($this->componentList, $this->getSettingsList(), 'strcasecmp'); } else { $componentsTmp = $this->componentList; } $components = []; foreach ($componentsTmp as $component) { $components['Krisawzm\\Embed\\Components\\' . $component] = $component . 'Embed'; } return $components; }
public function execute(&$value, &$error) { // check if we have a list $array_choice = $this->getParameter('array_choice', array()); // check if we have a config entry $config_choice = sfConfig::get($this->getParameter('config_choice', null)); $config_choice = is_null($config_choice) ? array() : array_keys($config_choice); // merge the two arrays (no need to array_unique it) $choice_list = array_merge($array_choice, $config_choice); // check if we have an exception list $exception_list = $this->getParameter('array_except', array()); // whether the entry value is unique or not $unique = $this->getParameter('unique', true); // check if this is lega values if ($unique && (is_array($value) || !in_array($value, $choice_list) || in_array($value, $exception_list)) || !$unique && (!is_array($value) || !count(array_uintersect($value, $choice_list, 'strcmp')) || count(array_uintersect($value, $exception_list, 'strcmp')))) { $error = $this->getParameter('bad_choice_error', 'bad choice error'); return false; } // check if we have an exclusive list $exclusive_list = $this->getParameter('array_exclusive', array()); $exclusive_error = false; if (!$unique && count($exclusive_list)) { $diff_list = array_udiff($choice_list, $exclusive_list, 'strcmp'); if (count(array_uintersect($value, $exclusive_list, 'strcmp')) && count(array_uintersect($value, $diff_list, 'strcmp'))) { $error = $this->getParameter('exclusive_choice_error', 'bad choice error'); return false; } } // check if we have an inclusive list $inclusive_list = $this->getParameter('array_inclusive', array()); $inclusive_error = false; if (count($inclusive_list)) { $diff_list = array_udiff($choice_list, $inclusive_list, 'strcmp'); if (count(array_uintersect($value, $inclusive_list, 'strcmp')) && !count(array_uintersect($value, $diff_list, 'strcmp'))) { $error = $this->getParameter('inclusive_choice_error', 'bad choice error'); return false; } } return true; }
<?php /* * proto array array_uintersect ( array $array1, array $array2 [, array $ ..., callback $data_compare_func] ) * Function is implemented in ext/standard/array.c */ class cr { private $priv_member; function cr($val) { $this->priv_member = $val; } static function comp_func_cr($a, $b) { if ($a->priv_member === $b->priv_member) { return 0; } return $a->priv_member > $b->priv_member ? 1 : -1; } } $a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1 => new cr(4), 2 => new cr(-15)); $b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1 => new cr(4), 2 => new cr(-15)); $result = array_uintersect($a, $b, array("cr", "comp_func_cr")); var_dump($result);
public function registerMounts(IUser $user, array $mounts) { // filter out non-proper storages coming from unit tests $mounts = array_filter($mounts, function (IMountPoint $mount) { return $mount->getStorage() && $mount->getStorage()->getCache(); }); /** @var ICachedMountInfo[] $newMounts */ $newMounts = array_map(function (IMountPoint $mount) use($user) { $storage = $mount->getStorage(); $rootId = (int) $storage->getCache()->getId(''); $storageId = (int) $storage->getStorageCache()->getNumericId(); // filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet) if ($rootId === -1) { return null; } else { return new CachedMountInfo($user, $storageId, $rootId, $mount->getMountPoint()); } }, $mounts); $newMounts = array_values(array_filter($newMounts)); $cachedMounts = $this->getMountsForUser($user); $mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) { // since we are only looking for mounts for a specific user comparing on root id is enough return $mount1->getRootId() - $mount2->getRootId(); }; /** @var ICachedMountInfo[] $addedMounts */ $addedMounts = array_udiff($newMounts, $cachedMounts, $mountDiff); /** @var ICachedMountInfo[] $removedMounts */ $removedMounts = array_udiff($cachedMounts, $newMounts, $mountDiff); $changedMounts = array_uintersect($newMounts, $cachedMounts, function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) { // filter mounts with the same root id and different mountpoints if ($mount1->getRootId() !== $mount2->getRootId()) { return -1; } return $mount1->getMountPoint() !== $mount2->getMountPoint() ? 0 : 1; }); foreach ($addedMounts as $mount) { $this->addToCache($mount); $this->mountsForUsers[$user->getUID()][] = $mount; } foreach ($removedMounts as $mount) { $this->removeFromCache($mount); $index = array_search($mount, $this->mountsForUsers[$user->getUID()]); unset($this->mountsForUsers[$user->getUID()][$index]); } foreach ($changedMounts as $mount) { $this->setMountPoint($mount); } }
} function comp_func_cr($a, $b) { if ($a->public_member === $b->public_member) { return 0; } return $a->public_member > $b->public_member ? 1 : -1; } $a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1 => new cr(4), 2 => new cr(-15)); $b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1 => new cr(4), 2 => new cr(-15)); /* array_uintersect() */ echo "begin ------------ array_uintersect() ---------------------------\n"; echo '$a=' . var_export($a, TRUE) . ";\n"; echo '$b=' . var_export($b, TRUE) . ";\n"; echo 'var_dump(array_uintersect($a, $b, "comp_func_cr"));' . "\n"; var_dump(array_uintersect($a, $b, "comp_func_cr")); echo "end ------------ array_uintersect() ---------------------------\n"; /* array_uintersect_assoc() */ echo "begin ------------ array_uintersect_assoc() ---------------------\n"; echo '$a=' . var_export($a, TRUE) . ";\n"; echo '$b=' . var_export($b, TRUE) . ";\n"; echo 'var_dump(array_uintersect_assoc($a, $b, "comp_func_cr"));' . "\n"; var_dump(array_uintersect_assoc($a, $b, "comp_func_cr")); echo "end ------------ array_uintersect_assoc() ---------------------\n"; /* array_uintersect_uassoc() - with ordinary function */ echo "begin ------------ array_uintersect_uassoc() with ordinary func -\n"; echo '$a=' . var_export($a, TRUE) . ";\n"; echo '$b=' . var_export($b, TRUE) . ";\n"; echo 'var_dump(array_uintersect_uassoc($a, $b, "comp_func_cr", "comp_func"));' . "\n"; var_dump(array_uintersect_uassoc($a, $b, "comp_func_cr", "comp_func")); echo "end ------------ array_uintersect_uassoc() with ordinary func -\n";
public static function filter_roles($user_roles, $master_roles) { return array_uintersect($master_roles, $user_roles, function ($a, $b) { return strcmp($a->shortname, $b->shortname); }); }
/** * 转发图度 * */ public function sendAction() { $post = $this->_request->getPost(); $post = array_merge(array('to' => '', 'cc' => ''), $post); $action = $post['action']; $type = $post['type']; // 判断操作,默认为发送 if (!in_array($action, array('send', 'save'))) { $action = 'send'; } // 判断类型,默认为任务 if (!in_array($type, array('task', 'discuss', 'notice'))) { $type = 'task'; } // 当前用户唯一ID $uniqueId = $this->_user['uniqueid']; // 是否现在发送 $isSend = true; // 是否已经发送过,可判读来源的图度是否发送过,已发送过的不允许保存为草稿 $isSent = false; // 是否转发 $isForward = !empty($post['forward']); // 是否来源于草稿 $isFromDraft = false; // 是否发起人 $isSender = false; // 是否执行人 $isAccpter = false; // 是否通知所有关联人员 $notifyAll = !empty($post['notifyall']); // 需要发送提醒的人 $notifyTo = array(); // 抄送人加入自己 $post['cc'] .= "\n" . $this->_user['email'] . ' ' . $this->_user['truename']; // 需要发送的地址,可能为空 $address = array('to' => $this->_formatRecipients($post['to']), 'cc' => $this->_formatRecipients($post['cc'], true)); // 需要发送的执行人,方便后面调用 $accepters = $address['to']; // 需要投递的联系人数据,保存用户唯一ID // uniqueid => array(isaccepter => {boolean}, accepterinfo => {string}) $recipients = array(); // 需要移除接受人的用户唯一ID $removeAccepters = array(); if (null === $this->_tudu) { return $this->json(false, $this->lang['tudu_not_exists']); } $fromTudu = $this->_tudu; // 日志记录内容 $tuduLog = array('action' => 'create', 'detail' => array()); $postLog = array('action' => 'create', 'detail' => array()); //////////////////////////// // 操作及参数判断 // 发送操作 if ('send' == $action) { $isAccpter = array_key_exists($this->_user['email'], $accepters); // 如果是转发 if ($isForward) { // 转发时,必须有图度存在 if (!$fromTudu) { $this->json(false, $this->lang['tudu_not_exists']); } // 图度组不能转发 if ($fromTudu->isTuduGroup) { $this->json(false, $this->lang['deny_forward_tudugroup']); } // 非图度执行人不能转发图度 if (!in_array($this->_user['email'], $fromTudu->accepter)) { $this->json(false, $this->lang['forbid_non_accepter_forward']); } // 执行人不能转发给自己 if ($isAccpter) { $this->json(false, $this->lang['forbid_forward_myself']); } foreach ($address['to'] as $a => $n) { if (in_array($a, $fromTudu->accepter, true)) { $this->json(false, sprintf($this->lang['user_is_accepter'], $n)); } } $tuduLog['action'] = Dao_Td_Log_Log::ACTION_TUDU_FORWARD; } // 保存图度 } else { if ('save' == $action) { $this->json(false); } } // 发送时参数判断,1.检查必须的参数,2.检查联系人是否存在。保存草稿时不需要这些判断 if ($isSend) { if ('task' == $type) { if (empty($address['to']) && (!$fromTudu || !$fromTudu->isTuduGroup)) { $this->json(false, $this->lang['missing_to']); } } else { if (empty($address['cc'])) { $this->json(false, $this->lang['missing_cc']); } } if (!$isForward && empty($post['subject'])) { $this->json(false, $this->lang['missing_subject']); } if (empty($post['content'])) { $this->json(false, $this->lang['missing_content']); } /* @var $daouser Dao_Td_Contact_Contact */ $daoContact = $this->getDao('Dao_Td_Contact_Contact'); /* @var $daoUser Dao_Md_User_User */ $daoUser = Oray_Dao::factory('Dao_Md_User_User'); $forwardInfo = array(); //被转发用户继承转发用户进度 if ($isForward) { $forwardInfo = array('forwardinfo' => $this->_user['truename'] . "\n" . time(), 'percent' => isset($post['percent']) ? (int) $post['percent'] : $fromTudu->selfPercent); } $users = $this->_deliver->getTuduUsers($this->_tudu->tuduId); $isAuth = $fromTudu->isAuth; // 外部联系人转发,仅从当前图度相关用户中检查 foreach ($address['to'] as $a => $name) { foreach ($users as $u) { if ($u['email'] == $a && $u['truename'] == $name) { $unId = $u['uniqueid']; $recipients[$unId] = array_merge(array('uniqueid' => $unId, 'role' => Dao_Td_Tudu_Tudu::ROLE_ACCEPTER, 'accepterinfo' => $a . ' ' . $name, 'percent' => 0, 'tudustatus' => 0, 'isforeign' => $u['isforeign'], 'authcode' => $u['isforeign'] && $isAuth ? Oray_Function::randKeys(4) : null), $forwardInfo); continue 2; } } $unId = Dao_Td_Contact_Contact::getContactId(); $info = Oray_Function::isEmail($a) ? $a . ' ' . $name : $name; $recipients[$unId] = array_merge(array('uniqueid' => $unId, 'role' => Dao_Td_Tudu_Tudu::ROLE_ACCEPTER, 'accepterinfo' => $info, 'percent' => 0, 'tudustatus' => 0, 'isforeign' => 1, 'authcode' => $isAuth ? Oray_Function::randKeys(4) : null), $forwardInfo); } // 去除原有执行人 if ($fromTudu) { $fromAccepter = $this->_deliver->getTuduAccepters($fromTudu->tuduId); $removeInfos = array(); $to = array(); foreach ($fromAccepter as $acpter) { if ($isForward) { if ($acpter['uniqueid'] == $uniqueId) { $removeAccepters[] = $this->_user['uniqueid']; $removeInfos[$this->_user['uniqueid']] = $acpter['accepterinfo']; continue; } } elseif (!isset($recipients[$acpter['uniqueid']]) || !is_array($recipients[$acpter['uniqueid']])) { $removeAccepters[] = $acpter['uniqueid']; $removeInfos[$acpter['uniqueid']] = $acpter['accepterinfo']; continue; } if (isset($recipients[$acpter['uniqueid']]['tudustatus'])) { $recipients[$acpter['uniqueid']]['percent'] = (int) $acpter['percent']; if (!$isForward && $acpter['tudustatus'] != 3) { $recipients[$acpter['uniqueid']]['tudustatus'] = $acpter['tudustatus']; } } $to[] = $acpter['accepterinfo']; $acceptInfo = explode(' ', $acpter['accepterinfo']); $notifyTo[] = $acceptInfo[0]; } $post['to'] = array_unique(array_merge($to, explode("\n", $post['to']))); $post['to'] = implode("\n", $post['to']); if ($fromTudu->isTuduGroup && !empty($removeAccepters)) { /** @var $daoGroup Dao_Td_Tudu_Group */ $daoGroup = $this->getDao('Dao_Td_Tudu_Group'); foreach ($removeAccepters as $unId) { if ($daoGroup->getChildrenCount($fromTudu->tuduId, $unId) > 0) { $this->json(false, sprintf($this->lang['user_has_divide'], $removeInfos[$unId])); } } } } // 处理抄送人 $arrCC = array(); // 外部联系人转发,仅从当前图度相关用户中检查 foreach ($address['cc'] as $a => $name) { foreach ($users as $u) { if ($u['email'] == $a && $u['truename'] == $name) { $unId = $u['uniqueid']; $recipients[$unId] = array('uniqueid' => $unId, 'role' => Dao_Td_Tudu_Tudu::ROLE_CC, 'accepterinfo' => $a . ' ' . $name, 'isforeign' => $u['isforeign'], 'authcode' => $u['isforeign'] && $isAuth ? Oray_Function::randKeys(4) : null); continue 2; } } $unId = Dao_Td_Contact_Contact::getContactId(); $recipients[$unId] = array('uniqueid' => $unId, 'role' => Dao_Td_Tudu_Tudu::ROLE_CC, 'accepterinfo' => $a . ' ' . $name, 'isforeign' => 1, 'authcode' => $isAuth ? Oray_Function::randKeys(4) : null); } // 编辑/转发,合并原有转发人信息 if (null !== $fromTudu) { $fromCC = array(); foreach ($fromTudu->cc as $addr => $cc) { if (!array_key_exists($addr, $address['cc'])) { $fromCC[] = $addr . ' ' . $cc[0]; } } $post['cc'] = implode("\n", $fromCC) . "\n" . $post['cc']; } // 通知所有人 if (in_array($type, array('notice', 'discuss')) || $notifyAll) { $notifyTo = array_merge($notifyTo, $arrCC); } if ($fromTudu) { $users = $this->_deliver->getTuduUsers($fromTudu->tuduId); foreach ($users as $item) { $labels = explode(',', $item['labels']); if (in_array('^t', $labels) && !in_array('^n', $labels)) { $user = $daoUser->getUser(array('uniqueid' => $item['uniqueid'])); $notifyTo[] = $user->address; } } } // 通知跳过当前操作用户(如果有) $notifyTo = array_unique(array_diff($notifyTo, array($this->_user['email']))); if ($type == 'notice' && !isset($post['remind'])) { $notifyTo = null; } //$recipients = array_unique($recipients); //var_dump($address); //var_dump($recipients); } //////////////////////////////// // 参数构造逻辑 // 基本参数 $params = array('orgid' => $this->_tudu->orgId, 'boardid' => $fromTudu ? $fromTudu->boardId : $post['bid'], 'email' => $this->_user['email'], 'type' => $type, 'subject' => isset($post['subject']) ? $post['subject'] : $fromTudu->subject, 'to' => $post['to'], 'cc' => $post['cc'], 'priority' => empty($post['priority']) ? 0 : (int) $post['priority'], 'privacy' => empty($post['privacy']) ? 0 : (int) $post['privacy'], 'status' => Dao_Td_Tudu_Tudu::STATUS_UNSTART, 'lastposttime' => $this->_timestamp, 'content' => $post['content'], 'attachment' => !empty($post['attach']) ? (array) $post['attach'] : array(), 'file' => !empty($post['file']) ? (array) $post['file'] : array()); if (isset($post['starttime'])) { $params['starttime'] = !empty($post['starttime']) ? strtotime($post['starttime']) : null; } if (isset($post['endtime'])) { $params['endtime'] = !empty($post['endtime']) ? strtotime($post['endtime']) : null; } if (isset($post['totaltime']) && is_numeric($post['totaltime'])) { $params['totaltime'] = round((double) $post['totaltime'], 2) * 3600; } if (isset($post['percent'])) { $params['percent'] = min(100, (int) $post['percent']); } if (isset($post['classid'])) { $params['classid'] = $post['classid']; } if (!empty($post['notifyall'])) { $params['notifyall'] = $post['notifyall']; } // 公告置顶 if ($type == 'notice' && !empty($params['endtime']) && $params['endtime'] >= strtotime('today')) { $params['istop'] = 1; } else { $params['istop'] = 0; } // 仅当草稿发送时更新创建时间 if (!$fromTudu || $isFromDraft && $isSend) { $params['createtime'] = $this->_timestamp; } // 更新图度操作时,一些参数设置 if (!isset($params['percent'])) { $params['percent'] = $fromTudu->percent; } if (isset($params['percent'])) { if (100 === $params['percent']) { $params['status'] = Dao_Td_Tudu_Tudu::STATUS_DONE; $params['cycle'] = null; } elseif ($params['percent'] > 0) { $params['status'] = Dao_Td_Tudu_Tudu::STATUS_DOING; } } // 处理日志记录内容 $tuduLog['detail'] = $params; $postLog['detail'] = array('content' => $params['content']); unset($tuduLog['detail']['cycle'], $tuduLog['detail']['vote'], $tuduLog['detail']['email'], $tuduLog['detail']['content'], $tuduLog['detail']['attachment'], $tuduLog['detail']['file'], $tuduLog['detail']['poster'], $tuduLog['detail']['posterinfo']); $logPrivacy = !$isSend; /////////////////////////////////// // 保存图度数据 $tuduId = $fromTudu->tuduId; $postId = $fromTudu->postId; // 内容的参数 $postParams = array('content' => $params['content'], 'lastmodify' => implode(chr(9), array($uniqueId, $this->_timestamp, $this->_user['truename'])), 'createtime' => $this->_timestamp, 'attachment' => $params['attachment'], 'isforeign' => 1, 'file' => !empty($post['file']) ? (array) $post['file'] : array()); // 从未发送时(草稿),相关的数据初始化(时效性的数据清除) if (!$isSent) { // 创建时间可相当于最先发送的时间 $params['createtime'] = $this->_timestamp; // 未发送过,不存在最后编辑 unset($postParams['lastmodify']); } // 不变更发起人 unset($params['from']); if ($isForward) { // 转发,更新最后转发人信息,不更新图度元数据,新建回复内容 unset($postParams['lastmodify']); $params['subject'] = $fromTudu->subject; $params['content'] = $fromTudu->content; $params['status'] = Dao_Td_Tudu_Tudu::STATUS_UNSTART; $params['accepttime'] = null; $params['lastforward'] = implode("\n", array($this->_user['truename'], time())); // 先发送新的回复 $postParams = array_merge($postParams, array('orgid' => $this->_tudu->orgId, 'boardid' => $fromTudu->boardId, 'tuduid' => $tuduId, 'uniqueid' => $this->_user['uniqueid'], 'poster' => $this->_user['truename'], 'email' => $this->_user['email'])); $postId = $this->_deliver->createPost($postParams); if (!$postId) { $this->json(false, $this->lang['save_failure']); } $this->getDao('Dao_Td_Tudu_Post')->sendPost($tuduId, $postId); $postLog['detail'] = $postParams; // 工作流程 $steps = $this->_manager->getSteps($tuduId)->toArray('stepid'); if (!empty($steps) && ($type = 'task')) { $currentStep = $this->_tudu->stepId && false === strpos($this->_tudu->stepId, '^') ? $steps[$this->_tudu->stepId] : array_pop($steps); // 当前为审批步骤 $stepNum = count($steps); $newSteps = array(); $currentTo = array_keys($this->_formatStepRecipients($params['to'])); $fromTo = array_keys($this->_tudu->to); $fromCount = count($fromTo); $isChangeTo = count($currentTo) != $fromCount || count(array_uintersect($fromTo, $currentTo, "strcasecmp")) != $fromCount; if ($isChangeTo) { $prevId = $currentStep['stepid']; $orderNum = $currentStep['ordernum']; $stepId = Dao_Td_Tudu_Step::getStepId(); $newSteps[$stepId] = array('orgid' => $this->_tudu->orgId, 'tuduid' => $tuduId, 'stepid' => $stepId, 'uniqueid' => $uniqueId, 'prevstepid' => $prevId, 'nextstepid' => '^end', 'type' => $this->_tudu->acceptMode ? Dao_Td_Tudu_Step::TYPE_CLAIM : Dao_Td_Tudu_Step::TYPE_EXECUTE, 'ordernum' => ++$orderNum, 'createtime' => time(), 'users' => $this->_formatStepRecipients($params['to'])); $params['stepid'] = $stepId; } // 移除后随未开始执行的步骤 foreach ($steps as $step) { if ($step['ordernum'] > $currentStep['ordernum']) { $this->_manager->deleteStep($tuduId, $step['stepid']); $stepNum--; } } foreach ($newSteps as $step) { if ($this->_manager->createStep($step)) { var_dump($step['users']); $recipients = $this->_prepareStepRecipients($this->_tudu->orgId, $uniqueId, $step['users']); $processIndex = $step['type'] == Dao_Td_Tudu_Step::TYPE_EXAMINE ? 0 : null; $this->_manager->addStepUsers($tuduId, $step['stepid'], $recipients, $processIndex); $stepNum++; } } $params['stepnum'] = $stepNum; } // 更新图度 if (!$this->_deliver->updateTudu($tuduId, $params)) { $this->json(false, $this->lang['save_failure']); } } // 过滤日志变更内容参数 if ($fromTudu) { $arrFromTudu = $fromTudu->toArray(); foreach ($tuduLog['detail'] as $k => $val) { // 记录增加抄送人 if ($k == 'cc') { $arr = explode("\n", $val); foreach ($arr as $idx => $v) { $ccArr = explode(' ', $v); if (array_key_exists($ccArr[0], $fromTudu->cc)) { unset($arr[$idx]); } } if (!$arr) { unset($tuduLog['detail']['cc']); } else { $tuduLog['detail']['cc'] = implode("\n", $arr); } continue; } // 过滤未更新字段 if (array_key_exists($k, $arrFromTudu) && $val == $arrFromTudu[$k]) { unset($tuduLog['detail'][$k]); } } // 内容没有变更 if (!$isForward) { if ($postLog['detail']['content'] == $fromTudu->content) { unset($postLog['detail']); } else { if (isset($postParams['lastmodify'])) { $postLog['detail']['lastmodify'] = $postParams['lastmodify']; } $postLog['detail']['createtime'] = $postParams['createtime']; } } if (empty($tuduLog['detail']['cc'])) { unset($tuduLog['detail']['cc']); } unset($tuduLog['detail']['from']); } // 写入操作日志 $this->_writeLog(Dao_Td_Log_Log::TYPE_TUDU, $tuduId, $tuduLog['action'], $tuduLog['detail'], $logPrivacy); if (!empty($postLog['detail'])) { $this->_writeLog(Dao_Td_Log_Log::TYPE_POST, $postId, $postLog['action'], $postLog['detail'], $logPrivacy); } $sendParams = array(); if ($type != 'task') { $sendParams['notice'] = $type == 'notice'; $sendParams['discuss'] = $type == 'discuss'; } // 删除需要移除的接受人 if ($removeAccepters) { if (!$this->_deliver->removeTuduAccepter($tuduId, $removeAccepters)) { $this->json(false, $this->lang['send_failure']); } } // 发送图度 if (!$this->_deliver->sendTudu($tuduId, $recipients, $sendParams)) { $this->json(false, $this->lang['send_failure']); } // 已发送的任务更新时,设置所有人为未读状态 if ($isSent) { $this->_manager->markAllUnread($tuduId); } // 转发任务时,设置当前关联用户为转发状态 if ($isForward) { $this->_manager->markForward($tuduId, $uniqueId); // 更新转发编辑后的任务进度 $this->_deliver->updateProgress($tuduId, $uniqueId, null); // 更新转发后的任务接受状态 $this->_deliver->updateLastAcceptTime($tuduId, $uniqueId, null); // 移除“我执行”标签 $this->_manager->deleteLabel($tuduId, $uniqueId, '^a'); } // 重新计算父级图度进度 if ($fromTudu && $fromTudu->parentId) { $this->_deliver->calParentsProgress($fromTudu->parentId); } if ('task' == $type) { // 发起人为当前执行人 if ($isAccpter) { // 自动接受任务 $this->_deliver->acceptTudu($tuduId, $uniqueId, null); // 添加我执行 $this->_deliver->addLabel($tuduId, $uniqueId, '^a'); // 接受添加日志 $this->_writeLog(Dao_Td_Log_Log::TYPE_TUDU, $tuduId, Dao_Td_Log_Log::ACTION_TUDU_ACCEPT, array('status' => Dao_Td_Tudu_Tudu::STATUS_DOING, 'accepttime' => time())); // 非当前执行人 } else { // 设为已读 $this->_deliver->markRead($tuduId, $uniqueId); } } $config = $this->_bootstrap->getOption('httpsqs'); // 插入消息队列 $httpsqs = new Oray_Httpsqs($config['host'], $config['port'], $config['chartset'], $config['name']); // 收发规则过滤 $data = implode(' ', array('tudu', 'filter', '', http_build_query(array('tsid' => $this->_tsId, 'tuduid' => $tuduId)))); $httpsqs->put($data, 'tudu'); // 发送外部邮件(如果有),处理联系人 $data = implode(' ', array('send', 'tudu', '', http_build_query(array('tsid' => $this->_tsId, 'tuduid' => $tuduId, 'uniqueid' => $this->_user['uniqueid'], 'to' => '')))); $httpsqs->put($data, 'send'); // IM提醒 if (!empty($notifyTo)) { $content = str_replace('%', '%%', mb_substr(preg_replace('/<[^>]+>/', '', $params['content']), 0, 100, 'UTF-8')); $names = array('task' => '图度', 'discuss' => '讨论', 'notice' => '公告'); $tpl = <<<HTML <strong>您刚收到一个新的{$names[$type]}</strong><br /> <a href="http://{$this->_request->getServer('HTTP_HOST')}/frame#m=view&tid=%s&page=1" target="_blank">%s</a><br /> 发起人:{$this->_user['truename']}<br /> 更新日期:%s<br /> {$content} HTML; $data = implode(' ', array('tudu', 'create', '', http_build_query(array('tuduid' => $this->_tudu->tuduId, 'from' => $this->_user['email'], 'to' => implode(',', $notifyTo), 'content' => sprintf($tpl, $this->_tudu->tuduId, $params['subject'], date('Y-m-d H:i:s', time())))))); $httpsqs->put($data); } $this->json(true, $this->lang['send_success'], $tuduId); }
/** * 显示打印页面 */ public function printAction() { $tuduId = $this->_request->getQuery('tid'); $vote = null; if (!$tuduId) { return $this->_redirect($this->_refererUrl); } /* @var $daoTudu Dao_Td_Tudu_Tudu */ $daoTudu = $this->getDao('Dao_Td_Tudu_Tudu'); $tudu = $daoTudu->getTuduById($this->_user->uniqueId, $tuduId, array()); if (null === $tudu) { Oray_Function::alert($this->lang['tudu_not_exists']); } $boards = $this->getBoards(false); $board = $boards[$tudu->boardId]; // 注:Receiver跟Accepter不同,前者指相关的接收人(参与人员),后者指图度的执行人 $isReceiver = $this->_user->uniqueId == $tudu->uniqueId && count($tudu->labels); $isModerators = array_key_exists($this->_user->userId, $board['moderators']); $inGroups = in_array($this->_user->userName, $board['groups'], true) || (bool) sizeof(array_uintersect($this->_user->groups, $board['groups'], "strcasecmp")); $isSuperModerator = !empty($board['parentid']) && array_key_exists($this->_user->userId, $boards[$board['parentid']]['moderators']); if (!$isReceiver && !$isModerators && !$isSuperModerator && ($tudu->privacy || $board['privacy'] || $inGroups)) { //$this->_redirect($_SERVER['HTTP_REFERER']); Oray_Function::alert($this->lang['perm_deny_view_tudu'], $_SERVER['HTTP_REFERER']); } // 读取投票 if ($tudu->special == Dao_Td_Tudu_Tudu::SPECIAL_VOTE) { /** * @var Dao_Td_Tudu_Vote */ $daoVote = $this->getDao('Dao_Td_Tudu_Vote'); // $vote = $daoVote->getVoteByTuduId($tudu->tuduId); // // $vote->getOptions(); // // $isVoted = $vote->isVoted($this->_user->uniqueId); // // $vote = $vote->toArray(); // $vote['expired'] = $vote['expiretime'] && time() > $vote['expiretime']; // $vote['isvoted'] = $isVoted; // $vote['enabled'] = !$vote['isvoted'] && !$vote['expired']; $vote = $daoVote->getVoteByTuduId($tudu->tuduId); $vote->getOptions(); $vote->countVoter(); $isVoted = $vote->isVoted($this->_user->uniqueId); $vote = $vote->toArray(); $vote['expired'] = $vote['expiretime'] && time() > $vote['expiretime']; $vote['isvoted'] = $isVoted; } $this->view->registModifier('tudu_format_content', array($this, 'formatContent')); /* @var $daoTudu Dao_Td_Tudu_Post */ $daoPost = $this->getDao('Dao_Td_Tudu_Post'); // 获取回复内容 $posts = $daoPost->getPosts(array('tuduid' => $tuduId), null, 'createtime ASC')->toArray(); $this->view->boardnav = $this->getBoardNav($tudu->boardId); $this->view->tudu = $tudu->toArray(); $this->view->posts = $posts; $this->view->vote = $vote; }
/** * gets core features and sorts features */ private function processFeatures() { $sortedFeatures = array(); // Topologically sort all features according to their dependency $features = array(); foreach ($this->features as $feature) { $features[] = $feature['name']; } $reverseDeps = array(); foreach ($features as $feature) { $reverseDeps[$feature] = array(); } $depCount = array(); foreach ($features as $feature) { $deps = $this->features[$feature]['deps']; $deps = array_uintersect($deps, $features, "strcasecmp"); $depCount[$feature] = count($deps); foreach ($deps as $dep) { $reverseDeps[$dep][] = $feature; } } while (!empty($depCount)) { $fail = true; foreach ($depCount as $feature => $count) { if ($count != 0) { continue; } $fail = false; $sortedFeatures[] = $feature; foreach ($reverseDeps[$feature] as $reverseDep) { $depCount[$reverseDep] -= 1; } unset($depCount[$feature]); } if ($fail && !empty($depCount)) { throw new GadgetException("Sorting feature dependence failed: it contains ring!"); } } $this->sortedFeatures = $sortedFeatures; }
/** * @return array Image formats, supported by current image manipulation driver. * The only formats that being checked are jpg, png and gif. */ public static function getSupportedFormats() { $imagine = Tygh::$app['image']; $supported_formats = array(); if ($imagine instanceof \Imagine\Imagick\Imagine) { $imagick = new \Imagick(); $supported_formats = array_uintersect(array('jpg', 'png', 'gif'), $imagick->queryFormats(), 'strcasecmp'); $supported_formats = array_map('strtolower', $supported_formats); $imagick->clear(); $imagick->destroy(); unset($imagick); } elseif ($imagine instanceof \Imagine\Gd\Imagine) { $gd_formats = imagetypes(); if ($gd_formats & IMG_JPEG) { $supported_formats[] = 'jpg'; } if ($gd_formats & IMG_PNG) { $supported_formats[] = 'png'; } if ($gd_formats & IMG_GIF) { $supported_formats[] = 'gif'; } } return $supported_formats; }
/** * Merges the initial results array, creating an union or intersection. * * The function also adds up the relevance values of the results object. * * @param array $results_arr * @param bool $kw_logic keyword logic (and, or, andex, orex) * @return array results array */ protected function merge_raw_results($results_arr, $kw_logic = "or") { /* * When using the "and" logic, the $results_arr contains the results in [term, term_reverse] * results format. These should not be intersected with each other, so this small code * snippet here divides the results array by groups of 2, then it merges ever pair to one result. * This way it turns into [term1, term1_reverse, term2 ...] array to [term1 union term1_reversed, ...] * * This is only neccessary with the "and" logic. Others work fine. */ if ($kw_logic == 'and') { $new_ra = array(); $i = 0; $tmp_v = array(); foreach ($results_arr as $_k => $_v) { if ($i & 1) { // odd, so merge the previous with the current $new_ra[] = array_merge($tmp_v, $_v); } $tmp_v = $_v; $i++; } $results_arr = $new_ra; } $final_results = array(); foreach ($results_arr as $results) { foreach ($results as $k => $r) { if (isset($final_results[$r->blogid . "x" . $r->id])) { $final_results[$r->blogid . "x" . $r->id]->relevance += $r->relevance; } else { $final_results[$r->blogid . "x" . $r->id] = $r; } } } if ($kw_logic == 'or' || $kw_logic == 'orex') { return $final_results; } foreach ($results_arr as $results) { $final_results = array_uintersect($final_results, $results, array($this, 'compare_results')); } return $final_results; }
/** * Handle classic CORS request to avoid duplicate code * @param string $type the kind of headers we would handle * @param array $requestHeaders CORS headers request by client * @param array $responseHeaders CORS response headers sent to the client */ protected function prepareAllowHeaders($type, $requestHeaders, &$responseHeaders) { $requestHeaderField = 'Access-Control-Request-' . $type; $responseHeaderField = 'Access-Control-Allow-' . $type; if (!isset($requestHeaders[$requestHeaderField], $this->cors[$requestHeaderField])) { return; } if (in_array('*', $this->cors[$requestHeaderField])) { $responseHeaders[$responseHeaderField] = $this->headerize($requestHeaders[$requestHeaderField]); } else { $requestedData = preg_split("/[\\s,]+/", $requestHeaders[$requestHeaderField], -1, PREG_SPLIT_NO_EMPTY); $acceptedData = array_uintersect($requestedData, $this->cors[$requestHeaderField], 'strcasecmp'); if (!empty($acceptedData)) { $responseHeaders[$responseHeaderField] = implode(', ', $acceptedData); } } }
protected function checkProductRestrictions(Context $context, $return_products = false, $display_error = true, $already_in_cart = false) { $selected_products = array(); // Check if the products chosen by the customer are usable with the cart rule if ($this->product_restriction) { $product_rule_groups = $this->getProductRuleGroups(); foreach ($product_rule_groups as $id_product_rule_group => $product_rule_group) { $eligible_products_list = array(); if (isset($context->cart) && is_object($context->cart) && is_array($products = $context->cart->getProducts())) { foreach ($products as $product) { $eligible_products_list[] = (int) $product['id_product'] . '-' . (int) $product['id_product_attribute']; } } if (!count($eligible_products_list)) { return !$display_error ? false : Tools::displayError('You cannot use this voucher in an empty cart'); } $product_rules = $this->getProductRules($id_product_rule_group); foreach ($product_rules as $product_rule) { switch ($product_rule['type']) { case 'attributes': $cart_attributes = Db::getInstance()->executeS(' SELECT cp.quantity, cp.`id_product`, pac.`id_attribute`, cp.`id_product_attribute` FROM `' . _DB_PREFIX_ . 'cart_product` cp LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_combination` pac ON cp.id_product_attribute = pac.id_product_attribute WHERE cp.`id_cart` = ' . (int) $context->cart->id . ' AND cp.`id_product` IN (' . implode(',', array_map('intval', $eligible_products_list)) . ') AND cp.id_product_attribute > 0'); $count_matching_products = 0; $matching_products_list = array(); foreach ($cart_attributes as $cart_attribute) { if (in_array($cart_attribute['id_attribute'], $product_rule['values'])) { $count_matching_products += $cart_attribute['quantity']; if ($already_in_cart && $this->gift_product == $cart_attribute['id_product'] && $this->gift_product_attribute == $cart_attribute['id_product_attribute']) { --$count_matching_products; } $matching_products_list[] = $cart_attribute['id_product'] . '-' . $cart_attribute['id_product_attribute']; } } if ($count_matching_products < $product_rule_group['quantity']) { return !$display_error ? false : Tools::displayError('You cannot use this voucher with these products'); } $eligible_products_list = array_uintersect($eligible_products_list, $matching_products_list, array('self', 'cartRuleCompare')); break; case 'products': $cart_products = Db::getInstance()->executeS(' SELECT cp.quantity, cp.`id_product` FROM `' . _DB_PREFIX_ . 'cart_product` cp WHERE cp.`id_cart` = ' . (int) $context->cart->id . ' AND cp.`id_product` IN (' . implode(',', array_map('intval', $eligible_products_list)) . ')'); $count_matching_products = 0; $matching_products_list = array(); foreach ($cart_products as $cart_product) { if (in_array($cart_product['id_product'], $product_rule['values'])) { $count_matching_products += $cart_product['quantity']; if ($already_in_cart && $this->gift_product == $cart_product['id_product']) { --$count_matching_products; } $matching_products_list[] = $cart_product['id_product'] . '-0'; } } if ($count_matching_products < $product_rule_group['quantity']) { return !$display_error ? false : Tools::displayError('You cannot use this voucher with these products'); } $eligible_products_list = array_uintersect($eligible_products_list, $matching_products_list, array('self', 'cartRuleCompare')); break; case 'categories': $cart_categories = Db::getInstance()->executeS(' SELECT cp.quantity, cp.`id_product`, cp.`id_product_attribute`, catp.`id_category` FROM `' . _DB_PREFIX_ . 'cart_product` cp LEFT JOIN `' . _DB_PREFIX_ . 'category_product` catp ON cp.id_product = catp.id_product WHERE cp.`id_cart` = ' . (int) $context->cart->id . ' AND cp.`id_product` IN (' . implode(',', array_map('intval', $eligible_products_list)) . ') AND cp.`id_product` <> ' . (int) $this->gift_product); $count_matching_products = 0; $matching_products_list = array(); foreach ($cart_categories as $cart_category) { if (in_array($cart_category['id_category'], $product_rule['values']) && !in_array($cart_category['id_product'] . '-' . $cart_category['id_product_attribute'], $matching_products_list)) { $count_matching_products += $cart_category['quantity']; $matching_products_list[] = $cart_category['id_product'] . '-' . $cart_category['id_product_attribute']; } } if ($count_matching_products < $product_rule_group['quantity']) { return !$display_error ? false : Tools::displayError('You cannot use this voucher with these products'); } // Attribute id is not important for this filter in the global list, so the ids are replaced by 0 foreach ($matching_products_list as &$matching_product) { $matching_product = preg_replace('/^([0-9]+)-[0-9]+$/', '$1-0', $matching_product); } $eligible_products_list = array_uintersect($eligible_products_list, $matching_products_list, array('self', 'cartRuleCompare')); break; case 'manufacturers': $cart_manufacturers = Db::getInstance()->executeS(' SELECT cp.quantity, cp.`id_product`, p.`id_manufacturer` FROM `' . _DB_PREFIX_ . 'cart_product` cp LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON cp.id_product = p.id_product WHERE cp.`id_cart` = ' . (int) $context->cart->id . ' AND cp.`id_product` IN (' . implode(',', array_map('intval', $eligible_products_list)) . ')'); $count_matching_products = 0; $matching_products_list = array(); foreach ($cart_manufacturers as $cart_manufacturer) { if (in_array($cart_manufacturer['id_manufacturer'], $product_rule['values'])) { $count_matching_products += $cart_manufacturer['quantity']; $matching_products_list[] = $cart_manufacturer['id_product'] . '-0'; } } if ($count_matching_products < $product_rule_group['quantity']) { return !$display_error ? false : Tools::displayError('You cannot use this voucher with these products'); } $eligible_products_list = array_uintersect($eligible_products_list, $matching_products_list, array('self', 'cartRuleCompare')); break; case 'suppliers': $cart_suppliers = Db::getInstance()->executeS(' SELECT cp.quantity, cp.`id_product`, p.`id_supplier` FROM `' . _DB_PREFIX_ . 'cart_product` cp LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON cp.id_product = p.id_product WHERE cp.`id_cart` = ' . (int) $context->cart->id . ' AND cp.`id_product` IN (' . implode(',', array_map('intval', $eligible_products_list)) . ')'); $count_matching_products = 0; $matching_products_list = array(); foreach ($cart_suppliers as $cart_supplier) { if (in_array($cart_supplier['id_supplier'], $product_rule['values'])) { $count_matching_products += $cart_supplier['quantity']; $matching_products_list[] = $cart_supplier['id_product'] . '-0'; } } if ($count_matching_products < $product_rule_group['quantity']) { return !$display_error ? false : Tools::displayError('You cannot use this voucher with these products'); } $eligible_products_list = array_uintersect($eligible_products_list, $matching_products_list, array('self', 'cartRuleCompare')); break; } if (!count($eligible_products_list)) { return !$display_error ? false : Tools::displayError('You cannot use this voucher with these products'); } } $selected_products = array_merge($selected_products, $eligible_products_list); } } if ($return_products) { return $selected_products; } return !$display_error ? true : false; }
public static function fullTextSearch($text, $start, $end, $category=NULL) { // the soap api interprets each string argument as a quoted string // search. multiple arguments are interpreted as an OR query // instead of AND query. so we employ some heuristics here to // narrow down search results // search in decreasing token size $tokens = split(' ', $text); usort($tokens, array(self, 'compare_strlen')); $longest_token = array_shift($tokens); // if all tokens are very short, use the full string if (strlen($longest_token) < 4) { $results = self::wordSearch($text, $start, $end, $category); return $results; } $results = self::wordSearch($longest_token, $start, $end, $category); foreach ($tokens as $token) { if (in_array($token, self::$common_words)) continue; $new_results = self::wordSearch($token, $start, $end, $category); $results = array_uintersect($results, $new_results, array(self, "compare_events")); // ignore the rest of the tokens if we're down to a few results if (count($results) < 5) { break; } } return $results; }
<?php $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red"); $array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red"); $array3 = array("a" => "grEEN", "white"); print_r(array_uintersect($array1, $array2, "strcasecmp")); print_r(array_uintersect($array1, $array2, $array3, "strcasecmp"));
/** * 读取用户下是否有可用的工作流 */ private function _getFlows() { /* @var $daoFlow Dao_Td_Flow_Flow */ $daoFlow = $this->getDao('Dao_Td_Flow_Flow'); $records = $daoFlow->getFlows(array('orgid' => $this->_user->orgId), null, 'createtime DESC'); $records = $records->toArray(); $flows = array(); foreach ($records as $key => $record) { if ($record['parentid']) { if (!in_array('^all', $record['avaliable']) && !(in_array($this->_user->userName, $record['avaliable'], true) || in_array($this->_user->address, $record['avaliable'], true)) && !sizeof(array_uintersect($this->_user->groups, $record['avaliable'], "strcasecmp")) && !($record['uniqueid'] == $this->_user->uniqueId)) { continue; } $flows[$record['parentid']]['children'][] =& $records[$key]; } } unset($records); return $flows; }
/** * 关注分区 */ public function attentionAction() { $this->_helper->viewRenderer->setNeverRender(); $post = $this->_request->getPost(); /* @var $daoBoard Dao_Td_Board_Board */ $daoBoard = $this->getDao('Dao_Td_Board_Board'); if (empty($post)) { $ret = $daoBoard->removeAllAttention($this->_user->orgId, $this->_user->uniqueId); if (!$ret) { return $this->json(false, $this->lang['add_board_attention_failure']); } return $this->json(true, $this->lang['add_board_attention_success'], null); } $member = $this->_request->getPost('member'); if (!is_array($member)) { $member = (array) $member; } if (!empty($member) && isset($member)) { $post = $this->_request->getPost(); $sucess = 0; // 移除用户所有快捷版块 $daoBoard->removeAllAttention($this->_user->orgId, $this->_user->uniqueId); foreach ($member as $idx) { $boardId = str_replace('_', '^', $post['boardid-' . $idx]); $orderNum = $post['ordernum-' . $idx]; if (!$boardId) { continue; } $boards = $this->getBoards(false); if (!isset($boards[$boardId])) { continue; } $board = $boards[$boardId]; $isSuperModerator = !empty($board['parentid']) && array_key_exists($this->_user->userId, $boards[$board['parentid']]['moderators']); $isModerator = array_key_exists($this->_user->userId, $board['moderators']); $inGroups = in_array($this->_user->userName, $board['groups'], true) || sizeof(array_uintersect($this->_user->groups, $board['groups'], "strcasecmp")); // 没有权限 if (!$isSuperModerator && !$isModerator && !$inGroups) { continue; } // 添加快捷版块 $ret = $daoBoard->addAttention($this->_user->orgId, $boardId, $this->_user->uniqueId, $orderNum); if ($ret) { $sucess++; } } if ($sucess <= 0) { return $this->json(false, $this->lang['add_board_attention_failure']); } $attentionBoards = $daoBoard->getAttentionBoards($this->_user->orgId, $this->_user->uniqueId); return $this->json(true, $this->lang['add_board_attention_success'], $attentionBoards); } else { $type = $this->_request->getPost('type'); $boardId = $this->_request->getPost('bid'); if (!$boardId) { return $this->json(false, $this->lang['board_not_exists']); } $type = $type == 'add' ? 'add' : 'remove'; $boards = $this->getBoards(false); if (!isset($boards[$boardId])) { return $this->json(false, $this->lang['board_not_exists']); } $board = $boards[$boardId]; $isSuperModerator = !empty($board['parentid']) && array_key_exists($this->_user->userId, $boards[$board['parentid']]['moderators']); $isModerator = array_key_exists($this->_user->userId, $board['moderators']); $inGroups = in_array($this->_user->userName, $board['groups'], true) || sizeof(array_uintersect($this->_user->groups, $board['groups'], "strcasecmp")); // 没有权限 if ($type == 'add' && !$isSuperModerator && !$isModerator && !$inGroups) { return $this->json(false, $this->lang['perm_deny_visit']); } if ($type == 'add') { $orderNum = $daoBoard->getAttentionBoardsMaxOrderNum($this->_user->orgId, $this->_user->uniqueId); $ret = $daoBoard->addAttention($this->_user->orgId, $boardId, $this->_user->uniqueId, $orderNum + 1); } else { $ret = $daoBoard->removeAttention($this->_user->orgId, $boardId, $this->_user->uniqueId); } if (!$ret) { return $this->json(false, $this->lang[$type . '_board_attention_failure']); } return $this->json(true, $this->lang[$type . '_board_attention_success']); } }