/** * 处理map reduce统计 * * @return string */ public function mrAction() { $cache = $this->cache(); $this->_worker->addFunction("mapreduce", function (\GearmanJob $job) use($cache) { try { $job->handle(); $params = unserialize($job->workload()); $out = $params['out']; $this->_data->setCollection($params['dataCollection']); $this->_data->setReadPreference(\MongoClient::RP_SECONDARY_PREFERRED); $dataModel = $this->_data; $statisticInfo = $params['statisticInfo']; $query = $params['query']; $method = $params['method']; $rst = mapReduce($out, $dataModel, $statisticInfo, $query, $method); var_dump($rst); $cache->remove($out); if (is_array($rst) && isset($rst['ok']) && $rst['ok'] === 0) { switch ($rst['code']) { case 500: $job->sendWarning('根据查询条件,未检测到有效的统计数据'); break; case 501: $job->sendWarning('MapReduce执行失败,原因:' . $rst['msg']); break; case 502: $job->sendWarning('程序正在执行中,请勿频繁尝试'); break; case 503: $job->sendWarning('程序异常:' . $rst['msg']); break; } $job->sendFail(); return false; } // sleep(30);//成功的操作等待30秒,用以确保复制集完成同步 $job->sendComplete('Complete'); return true; } catch (\Exception $e) { var_dump(exceptionMsg($e)); $job->sendException(exceptionMsg($e)); } }); while ($this->_worker->work()) { if ($this->_worker->returnCode() != GEARMAN_SUCCESS) { echo "return_code: " . $this->_worker->returnCode() . "\n"; } } return $this->response; }
/** * 通用worker组件 */ public function exportAction() { try { $cache = $this->cache(); $this->_worker->addFunction("commonworker", function (\GearmanJob $job) use($cache) { $job->handle(); $workload = $job->workload(); $params = unserialize($workload); $job->sendComplete('complete'); }); while ($this->_worker->work()) { if ($this->_worker->returnCode() != GEARMAN_SUCCESS) { echo "return_code: " . $this->_worker->returnCode() . "\n"; } } return $this->response; } catch (\Exception $e) { var_dump(exceptionMsg($e)); $job->sendException(exceptionMsg($e)); return false; } }
/** * 同步插件集合数据结构 * * @author young * @name 同步插件集合数据结构 * @version 2014.06.16 young */ public function syncAction() { try { $cache = $this->cache(); $this->_worker->addFunction("pluginCollectionSync", function (\GearmanJob $job) use($cache) { $job->handle(); $workload = $job->workload(); $key = md5($workload); $params = unserialize($workload); $project_id = $params['project_id']; $plugin_id = $params['plugin_id']; $datas = array(); $cursor = $this->_plugin_collection->find(array('plugin_id' => $plugin_id)); if ($cursor->count() > 0) { while ($cursor->hasNext()) { $row = $cursor->getNext(); $this->_plugin_collection->syncPluginCollection($project_id, $plugin_id, $row['alias']); } $cache->remove($key); $job->sendComplete('Complete'); return true; } else { $cache->remove($key); $job->sendException('程序异常:' . $rst['msg']); return false; } }); while ($this->_worker->work()) { if ($this->_worker->returnCode() != GEARMAN_SUCCESS) { echo "return_code: " . $this->_worker->returnCode() . "\n"; } } return $this->response; } catch (\Exception $e) { var_dump(exceptionMsg($e)); $job->sendException(exceptionMsg($e)); return false; } }
/** * 创建一个服务 */ public function soap($uri, $className, $config = null) { if (isset($_GET['wsdl'])) { $autodiscover = new AutoDiscover(); $autodiscover->setClass($className)->setUri($uri); return $autodiscover->toXml(); } else { $wsdl = strpos($uri, '?') === false ? $uri . '?wsdl' : $uri . '&wsdl'; $server = new SoapServer($wsdl); $obj = $config == null ? new $className() : new $className($config); $server->setObject($obj); $server->handle(); $response = $server->getLastRequest(); if ($response instanceof \SoapFault) { $response = exceptionMsg($response); $this->log($response); } return $response; } }
public function __call($functionName, $arguments) { if ($this->_asyncResult == null) { $this->_asynchronous = false; $this->_asyncAction = null; if (preg_match('/Async$/', $functionName) == 1) { $this->_asynchronous = true; $functionName = str_replace('Async', '', $functionName); $this->asyncFunctionName = $functionName; } } try { $result = @parent::__call($functionName, $arguments); } catch (SoapFault $e) { throw new Exception(exceptionMsg($e)); } if ($this->_asynchronous == true) { return $this->_asyncAction; } return $result; }
/** * 处理数据中的关联数据 */ private function dealRshData($project_id, $collection_id, $field) { try { $rshData = array(); $rsh = $this->_structure->getRshFields($collection_id); if (!empty($rsh) && isset($rsh[$field])) { $rshCollection = $this->_collection->getCollectionIdByAlias($project_id, $rsh[$field]); // 获取被关联集合的结构 $rshKeyValue = $this->_structure->getComboboxKeyValueField($rshCollection); $model = $this->collection()->secondary(iCollectionName($rshCollection)); $cursor = $model->find(array(), array($rshKeyValue['rshCollectionKeyField'] => true, $rshKeyValue['rshCollectionValueField'] => true)); while ($cursor->hasNext()) { $row = $cursor->getNext(); $key = $row[$rshKeyValue['rshCollectionValueField']]; $value = isset($row[$rshKeyValue['rshCollectionKeyField']]) ? $row[$rshKeyValue['rshCollectionKeyField']] : ''; if ($key instanceof \MongoId) { $key = $key->__toString(); } $rshData[$key] = $value; } } return $rshData; } catch (\Exception $e) { fb(exceptionMsg($e), 'LOG'); } }
/** * 导入数据到集合内 */ public function importAction() { try { $importSheetName = trim($this->params()->fromPost('sheetName', null)); $file = $this->params()->fromFiles('import', null); if ($importSheetName == null) { return $this->msg(false, '请设定需要导入的sheet'); } if ($file == null) { return $this->msg(false, '请上传Excel数据表格文件'); } if ($file['error'] === UPLOAD_ERR_OK) { $fileName = $file['name']; $filePath = $file['tmp_name']; $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); switch ($ext) { case 'xlsx': $inputFileType = 'Excel2007'; break; default: return $this->msg(false, '很抱歉,您上传的文件格式无法识别,格式要求:*.xlsx'); } $objReader = \PHPExcel_IOFactory::createReader($inputFileType); $objReader->setReadDataOnly(true); $objReader->setLoadSheetsOnly($importSheetName); $objPHPExcel = $objReader->load($filePath); if (!in_array($importSheetName, array_values($objPHPExcel->getSheetNames()))) { return $this->msg(false, 'Sheet:"' . $importSheetName . '",不存在,请检查您导入的Excel表格'); } $objPHPExcel->setActiveSheetIndexByName($importSheetName); $objActiveSheet = $objPHPExcel->getActiveSheet(); $sheetData = $objActiveSheet->toArray(null, true, true, true); $objPHPExcel->disconnectWorksheets(); unset($objReader, $objPHPExcel, $objActiveSheet); if (empty($sheetData)) { return $this->msg(false, '请确认表格中未包含有效数据,请复核'); } $firstRow = array_shift($sheetData); if (count($firstRow) == 0) { return $this->msg(false, '标题行数据为空'); } $titles = array(); foreach ($firstRow as $col => $value) { $value = trim($value); if (in_array($value, array_keys($this->_schema), true)) { $titles[$col] = $this->_schema[$value]; } else { if (in_array($value, array_values($this->_schema), true)) { $titles[$col] = $value; } } } if (count($titles) == 0) { return $this->msg(false, '无匹配的标题或者标题字段,请检查导入数据的格式是否正确'); } array_walk($sheetData, function ($row, $rowNumber) use($titles) { $insertData = array(); foreach ($titles as $col => $colName) { $insertData[$colName] = formatData($row[$col], $this->_fields[$colName]); } $this->_data->insertByFindAndModify($insertData); unset($insertData); }); unset($sheetData); return $this->msg(true, '导入成功'); } else { return $this->msg(false, '上传文件失败'); } } catch (\Exception $e) { fb(exceptionMsg($e), \FirePHP::LOG); return $this->msg(false, '导入失败,发生异常'); } }
/** * 对于集合进行了任何操作,那么出发联动事件,联动修改其他集合的相关数据 * 提交全部POST参数以及系统默认的触发参数__TRIGER__ * $_POST['__TRIGER__']['collection'] 触发事件集合的名称 * $_POST['__TRIGER__']['controller'] 触发控制器 * $_POST['__TRIGER__']['action'] 触发动作 * 为了确保调用安全,签名方法为所有POST参数按照字母顺序排列,构建的字符串substr(sha1(k1=v1&k2=v2连接密钥),0,32),做个小欺骗,让签名看起来很像MD5的。 */ public function __destruct() { fastcgi_finish_request(); try { $controller = $this->params('controller'); $action = $this->params('action'); $_POST['__TRIGER__'] = array('collection' => $this->getCollectionAliasById($this->_collection_id), 'controller' => $controller, 'action' => $action); $collectionInfo = $this->_collection->findOne(array('_id' => myMongoId($this->_collection_id), 'isAutoHook' => true)); if ($collectionInfo !== null && isset($collectionInfo['hook']) && filter_var($collectionInfo['hook'], FILTER_VALIDATE_URL) !== false) { $sign = dataSignAlgorithm($_POST, $collectionInfo['hookKey']); $_POST['__SIGN__'] = $sign; $response = doPost($collectionInfo['hook'], $_POST); $this->_collection->update(array('_id' => $collectionInfo['_id']), array('$set' => array('hookLastResponseResult' => $response))); } } catch (\Exception $e) { $this->log(exceptionMsg($e)); } return false; }
/** * 进行mongoid和tostring之间的转换 * 增加函数mongoid用于mongoid和字符串形式之间的自动转换 * * @param mixed $var * @return string MongoId */ function myMongoId($var = null) { if (is_array($var)) { $newArray = array(); foreach ($var as $row) { if ($row instanceof MongoId) { $newArray[] = $row->__toString(); } else { try { $newArray[] = new MongoId($row); } catch (Exception $e) { continue; } } } return $newArray; } else { if ($var instanceof MongoId) { return $var->__toString(); } else { $var = !empty($var) && strlen($var) == 24 ? $var : null; try { return new MongoId($var); } catch (Exception $e) { fb(exceptionMsg($e), 'LOG'); return new MongoId(); } } } }
/** * 导出数据 */ public function exportAction() { try { $cache = $this->cache(); $this->_worker->addFunction("dataExport", function (\GearmanJob $job) use($cache) { $job->handle(); $workload = $job->workload(); $params = unserialize($workload); $scope = $params['scope']; $collection_id = $params['collection_id']; $query = $params['query']; $fields = $params['fields']; $exportKey = md5($workload); $exportGearmanKey = md5($scope->_collection_id . serialize($query)); // 获取映射关系,初始化数据集合model $mapCollection = $this->_mapping->findOne(array('project_id' => $scope->_project_id, 'collection_id' => $scope->_collection_id, 'active' => true)); if ($mapCollection != null) { $this->_data->setCollection($mapCollection['collection'], $mapCollection['database'], $mapCollection['cluster']); } else { $this->_data->setCollection(iCollectionName($collection_id)); } $this->_data->setReadPreference(\MongoClient::RP_SECONDARY_PREFERRED); $cursor = $this->_data->find($query, $fields); $excelDatas = array(); // 保持拥有全部的字段名,不存在错乱的想象 $fieldNames = array_keys($fields); while ($cursor->hasNext()) { $row = $cursor->getNext(); $tmp = array(); foreach ($fieldNames as $key) { $tmp[$key] = isset($row[$key]) ? $row[$key] : ''; } $excelDatas[] = $tmp; unset($tmp); } // 在导出数据的情况下,将关联数据显示为关联集合的显示字段数据 $rshData = array(); foreach ($scope->_rshCollection as $_id => $detail) { $_id = $this->getCollectionIdByAlias($scope->_project_id, $_id); $model = $this->collection()->secondary(iCollectionName($_id)); $cursor = $model->find(array(), array($detail['rshCollectionKeyField'] => true, $detail['rshCollectionValueField'] => true)); $datas = array(); while ($cursor->hasNext()) { $row = $cursor->getNext(); $key = $row[$detail['rshCollectionValueField']]; $value = isset($row[$detail['rshCollectionKeyField']]) ? $row[$detail['rshCollectionKeyField']] : ''; if ($key instanceof \MongoId) { $key = $key->__toString(); } if (!empty($key)) { $datas[$key] = $value; } } $rshData[$detail['collectionField']] = $datas; } // 结束 convertToPureArray($excelDatas); array_walk($excelDatas, function (&$value, $key) use($rshData, $fields) { $loop = function ($value, $tmp) { $new = $value; $len = count($tmp); for ($i = 0; $i < $len; $i++) { if (isset($new[$tmp[$i]])) { $new = $new[$tmp[$i]]; } else { return ''; } } return $new; }; foreach ($fields as $k => $v) { if (strpos($k, '.') !== false) { $tmp = explode('.', $k); $value[$k] = $loop($value, $tmp); } } ksort($value); array_walk($value, function (&$cell, $field) use($rshData) { if (isset($rshData[$field])) { $cell = isset($rshData[$field][$cell]) ? $rshData[$field][$cell] : ''; } }); }); $title = array(); ksort($fields); foreach (array_keys($fields) as $field) { $title[] = isset($scope->_title[$field]) ? $scope->_title[$field] : $field; } $excel = array('title' => $title, 'result' => $excelDatas); $temp = tempnam(sys_get_temp_dir(), 'gearman_export_'); arrayToExcel($excel, $exportKey, $temp); $cache->save(file_get_contents($temp), $exportKey, 60); unlink($temp); $cache->remove($exportGearmanKey); $job->sendComplete('complete'); }); while ($this->_worker->work()) { if ($this->_worker->returnCode() != GEARMAN_SUCCESS) { echo "return_code: " . $this->_worker->returnCode() . "\n"; } } return $this->response; } catch (\Exception $e) { var_dump(exceptionMsg($e)); $job->sendException(exceptionMsg($e)); return false; } }
/** * 编辑某些字段 * * @author young * @name 编辑某些字段 * @version 2013.11.14 young * @return JsonModel */ public function editAction() { $_id = $this->params()->fromPost('_id', null); $datas = array(); $datas['collection_id'] = $this->_collection_id; $datas['plugin_collection_id'] = $this->_plugin_collection_id; $datas['plugin_id'] = $this->_plugin_id; $datas['field'] = $this->params()->fromPost('field', null); $datas['label'] = $this->params()->fromPost('label', null); $datas['type'] = $this->params()->fromPost('type', null); $datas['filter'] = (int) filter_var($this->params()->fromPost('filter', 0), FILTER_SANITIZE_NUMBER_INT); $datas['searchable'] = filter_var($this->params()->fromPost('searchable', false), FILTER_VALIDATE_BOOLEAN); $datas['main'] = filter_var($this->params()->fromPost('main', false), FILTER_VALIDATE_BOOLEAN); $datas['required'] = filter_var($this->params()->fromPost('required', false), FILTER_VALIDATE_BOOLEAN); $datas['export'] = filter_var($this->params()->fromPost('export', false), FILTER_VALIDATE_BOOLEAN); $datas['isFatherField'] = filter_var($this->params()->fromPost('isFatherField', false), FILTER_VALIDATE_BOOLEAN); $datas['rshCollection'] = $this->params()->fromPost('rshCollection', ''); $datas['isBoxSelect'] = filter_var($this->params()->fromPost('isBoxSelect', ''), FILTER_VALIDATE_BOOLEAN); $datas['rshType'] = 'combobox'; $datas['rshKey'] = filter_var($this->params()->fromPost('rshKey', false), FILTER_VALIDATE_BOOLEAN); $datas['rshValue'] = filter_var($this->params()->fromPost('rshValue', false), FILTER_VALIDATE_BOOLEAN); $datas['showImage'] = filter_var($this->params()->fromPost('showImage', false), FILTER_VALIDATE_BOOLEAN); $datas['orderBy'] = (int) filter_var($this->params()->fromPost('orderBy', 0), FILTER_VALIDATE_INT); $datas['isQuick'] = filter_var($this->params()->fromPost('isQuick', false), FILTER_VALIDATE_BOOLEAN); $datas['quickTargetCollection'] = trim($this->params()->fromPost('quickTargetCollection', '')); $datas['rshSearchCondition'] = trim($this->params()->fromPost('rshSearchCondition', '')); $datas['isLinkageMenu'] = filter_var($this->params()->fromPost('isLinkageMenu', false), FILTER_VALIDATE_BOOLEAN); $datas['linkageClearValueField'] = trim($this->params()->fromPost('linkageClearValueField', '')); $datas['linkageSetValueField'] = trim($this->params()->fromPost('linkageSetValueField', '')); $datas['cdnUrl'] = trim($this->params()->fromPost('cdnUrl', '')); $datas['xTemplate'] = trim($this->params()->fromPost('xTemplate', '')); if (in_array(strtolower($datas['field']), $this->_filter, true)) { return $this->msg(false, '保留字段不允许作为字段名称,保留字段为:' . join(',', $this->_filter)); } if ($datas['type'] !== 'filefield' && !empty($datas['cdnUrl'])) { return $this->msg(false, '只有当输入类型为“文件类型”时,才需要设定文件资源域名'); } if ($datas['field'] == null) { return $this->msg(false, '请填写字段名称'); } if (!$this->checkFieldName($datas['field'])) { return $this->msg(false, '字段名必须为以英文字母开始的“字母、数字、下划线”的组合,“点”标注子属性时,子属性必须以字母开始'); } if ($datas['label'] == null) { return $this->msg(false, '请填写字段描述'); } if ($datas['type'] == null) { return $this->msg(false, '请选择字段类型'); } if ($datas['rshSearchCondition'] !== '') { if (isJson($datas['rshSearchCondition'])) { try { $datas['rshSearchCondition'] = Json::decode($datas['rshSearchCondition'], Json::TYPE_ARRAY); } catch (\Exception $e) { fb(exceptionMsg($e), 'LOG'); return $this->msg(false, '关联集合约束查询条件的json格式错误'); } } else { return $this->msg(false, '关联集合约束查询条件的json格式错误'); } } if ($datas['isQuick'] === true) { if ($datas['type'] !== 'arrayfield') { return $this->msg(false, '快速录入字段,输入类型必须是“数组”'); } if ($datas['quickTargetCollection'] === '') { return $this->msg(false, '请选快速录入的目标集合'); } } $oldStructureInfo = $this->_structure->findOne(array('_id' => myMongoId($_id))); if ($this->checkExist('field', $datas['field'], array('collection_id' => $this->_collection_id)) && $oldStructureInfo['field'] != $datas['field']) { return $this->msg(false, '字段名称已经存在'); } if ($this->checkExist('label', $datas['label'], array('collection_id' => $this->_collection_id)) && $oldStructureInfo['label'] != $datas['label']) { return $this->msg(false, '字段描述已经存在'); } if ($datas['isBoxSelect']) { if ($datas['type'] !== 'arrayfield') { return $this->msg(false, '启用多选项时,请设定输入类型为“数组”'); } if (empty($datas['rshCollection'])) { return $this->msg(false, '启用多选项时,必须设定“关联结合”'); } } if ($datas['isFatherField']) { if (empty($datas['rshCollection'])) { return $this->msg(false, '复选项,必须设定“关联结合”,且关联结合为自身'); } } // 如果修改了字段名称,那么对于数据集合中的对应字段进行重命名操作 if ($oldStructureInfo['field'] !== $datas['field']) { if ($this->_mapping->getMapping($this->_collection_id) !== null) { return $this->msg(false, '当前集合开启了映射,无法修改字段名'); } $dataCollection = $this->collection(iCollectionName($this->_collection_id)); if ($dataCollection instanceof \MongoCollection) { $rstRename = $dataCollection->update(array(), array('$rename' => array($oldStructureInfo['field'] => $datas['field']))); $datas['__OLD_FIELD__'] = $oldStructureInfo['field']; } } $this->_structure->update(array('_id' => myMongoId($_id)), array('$set' => $datas)); // 同步插件中的数据结构 $this->_plugin_structure->sync($datas); return $this->msg(true, '编辑信息成功'); }
/** * 复制一个项目 */ public function cloneAction() { try { $projectId = $this->params()->fromQuery("projectId", ''); $targetProjectId = $this->params()->fromQuery("targetProjectId", ''); // 获取复制项目表 $source_formIds = $this->params()->fromQuery('forms', array()); // 是否复制数据 $isCopyData = intval($this->params()->fromQuery("isCopyData", 0)); // 是否是同一个数据库 $isSameProject = $projectId == $targetProjectId; if (!empty($projectId)) { $projectInfo = $this->_project->findOne(array('_id' => myMongoId($projectId))); if (empty($projectInfo)) { return $this->msg(false, '源项目不存在,无法复制'); } $checkProject = $this->_project->findOne(array('_id' => myMongoId($targetProjectId))); if (empty($checkProject)) { return $this->msg(false, '目标项目不存在,无法复制'); } resetTimeMemLimit(); // 获取该项目下的所有表,循环复制 $formIds = array(); $query = array(); $query['projectId'] = $projectId; if (count($source_formIds) > 0) { foreach ($source_formIds as $k => &$v) { $v = myMongoId($v); } } $query['_id'] = array('$in' => $source_formIds); $collection = $this->model('Idatabase\\Model\\Collection'); $cursor = $collection->find($query); while ($cursor->hasNext()) { $formInfo = $cursor->getNext(); // 复制表 $newFormInfo = $this->cloneForm($targetProjectId, $formInfo, $isCopyData); // 返回旧表的ID和新表ID的对应数组 $formIds[$formInfo['_id']->__toString()] = $newFormInfo['newFormID']; } // 更新结构表的外键关联信息及数据关系 $this->updateRshDataForm($formIds); return $this->msg(true, '复制项目成功'); } else { return $this->msg(false, '请提交你要复制的项目'); } } catch (\Exception $e) { $exceptMsg = exceptionMsg($e); return $this->msg(false, $exceptMsg); } }
* new developers to be productive with a fresh skeleton. It allows autoloading * to be correctly configured, regardless of the installation method and keeps * the use of composer completely optional. This setup should work fine for * most users, however, feel free to configure autoloading however you'd like. */ // Composer autoloading if (file_exists('vendor/autoload.php')) { $loader = (include 'vendor/autoload.php'); } if (!class_exists('Zend\\Loader\\AutoloaderFactory')) { exit('Unable to load ZF2. Run `php composer.phar install` or define a ZF2_PATH environment variable.'); } // 加载自己的函数库 if (file_exists(__DIR__ . '/library/function.php')) { include __DIR__ . '/library/function.php'; } // 加载自己的函数库 $myAutoLoaderClass = array('My' => __DIR__ . '/library/My'); try { if (is_array($myAutoLoaderClass)) { foreach ($myAutoLoaderClass as $namespace => $libraryPath) { if (is_dir($libraryPath)) { Zend\Loader\AutoloaderFactory::factory(array('Zend\\Loader\\StandardAutoloader' => array('namespaces' => array($namespace => $libraryPath)))); } else { throw new Exception($libraryPath . ' is not a dir'); } } } } catch (Exception $e) { exit(exceptionMsg($e)); }
/** * 保存数据,$datas中如果包含_id属性,那么将更新_id的数据,否则创建新的数据 * * @param string $datas * @throws \SoapFault * @return string */ public function save($datas) { try { $datas = $this->toArray($datas); $rst = $this->_model->saveRef($datas); return $this->result(array('datas' => $datas, 'rst' => $rst)); } catch (\SoapFault $e) { return $this->result(exceptionMsg($e)); } }
/** * 执行map reduce操作,为了防止数据量过大,导致无法完成mapreduce,统一采用集合的方式,取代内存方式 * 内存方式,不允许执行过程的数据量量超过物理内存的10%,故无法进行大数量分析工作。 * * @param array $command */ public function mapReduce($out = null, $map, $reduce, $query = array(), $finalize = null, $method = 'replace', $scope = null, $sort = array('$natural' => 1), $limit = null) { if ($out == null) { $out = md5(serialize(func_get_args())); } try { // map reduce执行锁管理开始 $locks = new self($this->_configInstance, 'locks', DB_MAPREDUCE, $this->_cluster); $locks->setReadPreference(\MongoClient::RP_PRIMARY_PREFERRED); $checkLock = function ($out) use($locks) { $check = $locks->findOne(array('out' => $out)); if ($check == null) { $locks->insert(array('out' => $out, 'isRunning' => true, 'expire' => new \MongoDate(time() + 300))); return false; } else { if (isset($check['isRunning']) && $check['isRunning']) { return true; } if ($check['isRunning'] && isset($check['expire']) && $check['expire'] instanceof \MongoDate) { if ($check['expire']->sec > time()) { return true; } else { $releaseLock($out); return false; } } $locks->update(array('out' => $out), array('$set' => array('isRunning' => true, 'expire' => new \MongoDate(time() + 300)))); return false; } }; $releaseLock = function ($out, $rst = null) use($locks) { return $locks->update(array('out' => $out), array('$set' => array('isRunning' => false, 'rst' => is_string($rst) ? $rst : Json::encode($rst)))); }; $failure = function ($code, $msg) { if (is_array($msg)) { $msg = Json::encode($msg); } return array('ok' => 0, 'code' => $code, 'msg' => $msg); }; // map reduce执行锁管理结束 if (!$checkLock($out)) { $command = array(); $command['mapreduce'] = $this->_collection; $command['map'] = $map instanceof \MongoCode ? $map : new \MongoCode($map); $command['reduce'] = $reduce instanceof \MongoCode ? $reduce : new \MongoCode($reduce); $command['query'] = $this->appendQuery($query); if (!empty($finalize)) { $command['finalize'] = $finalize instanceof \MongoCode ? $finalize : new \MongoCode($finalize); } if (!empty($sort)) { $command['sort'] = $sort; } if (!empty($limit)) { $command['limit'] = $limit; } if (!empty($scope)) { $command['scope'] = $scope; } $command['verbose'] = true; if (!in_array($method, array('replace', 'merge', 'reduce'), true)) { $method = 'replace'; } $command['out'] = array($method => $out, 'db' => DB_MAPREDUCE, 'sharded' => false, 'nonAtomic' => in_array($method, array('merge', 'reduce'), true) ? true : false); $rst = $this->command($command); $releaseLock($out, $rst); if ($rst['ok'] == 1) { if ($rst['counts']['emit'] > 0 && $rst['counts']['output'] > 0) { $outMongoCollection = new self($this->_configInstance, $out, DB_MAPREDUCE, $this->_cluster); $outMongoCollection->setNoAppendQuery(true); return $outMongoCollection; } return $failure(500, $rst['counts']); } else { return $failure(501, $rst); } } else { return $failure(502, '程序正在执行中,请勿频繁尝试'); } } catch (\Exception $e) { if (isset($releaseLock) && isset($failure)) { $releaseLock($out, exceptionMsg($e)); return $failure(503, exceptionMsg($e)); } var_dump(exceptionMsg($e)); } }
/** * 批量更新数据 * * @author young * @name 批量更新数据,只更新特定数据,不包含2的坐标和文件字段 * @version 2013.12.10 young * @return JsonModel */ public function saveAction() { try { $updateInfos = $this->params()->fromPost('updateInfos', null); try { $updateInfos = Json::decode($updateInfos, Json::TYPE_ARRAY); } catch (\Exception $e) { return $this->msg(false, '无效的json字符串'); } if (!is_array($updateInfos)) { return $this->msg(false, '更新数据无效'); } foreach ($updateInfos as $row) { $_id = $row['_id']; unset($row['_id']); $oldDataInfo = $this->_data->findOne(array('_id' => myMongoId($_id))); if ($oldDataInfo != null) { $datas = array_intersect_key($row, $this->_schema['post']); if (!empty($datas)) { try { $datas = $this->dealData($datas); } catch (\Zend\Json\Exception\RuntimeException $e) { return $this->msg(false, $e->getMessage() . $this->_jsonExceptMessage); } try { $__OLD_DATA__ = $this->_data->findOne(array('_id' => myMongoId($_id))); $this->_data->update(array('_id' => myMongoId($_id)), array('$set' => $datas)); // 快捷录入数据处理 $datas['_id'] = myMongoId($_id); $datas['__OLD_DATA__'] = $__OLD_DATA__; $this->quickOperation($datas); } catch (\Exception $e) { return $this->msg(false, exceptionMsg($e)); } } } } return $this->msg(true, '更新数据成功'); } catch (\exception $e) { return $this->msg(false, $e->getTraceAsString()); } }