Пример #1
0
/**
 * 
 * @param array $arData with element "arDataName"
 * @param string $strRequest, for example: #RC#arDataName#-2#field1#field2#...#fieldN
 */
function BXTasksParseAndGetDynaParamValue($arData, $strRequest)
{
    CTaskAssert::assert(is_array($arData) && is_string($strRequest) && substr($strRequest, 0, 4) === '#RC#');
    $dataCount = count($arData);
    $strToParse = substr($strRequest, 4);
    $arrayToParse = explode('#', $strToParse);
    CTaskAssert::assert(is_array($arrayToParse) && count($arrayToParse) >= 3 && isset($arData[$arrayToParse[0]]) && CTaskAssert::isLaxIntegers($arrayToParse[1]) && $arrayToParse[1] < 0);
    $arRequestedData = $arData[$arrayToParse[0]];
    $curDataIndex = count($arRequestedData) - 1;
    $deltaIndex = (int) $arrayToParse[1];
    $requestedIndex = $curDataIndex + $deltaIndex + 1;
    // +1 because last data item mustn't be in data array yet
    if (!isset($arRequestedData[$requestedIndex])) {
        return null;
    }
    // Now, iterate throws given fields
    $maxIndex = count($arrayToParse) - 1;
    $arIteratedData = $arRequestedData[$requestedIndex];
    for ($i = 2; $i <= $maxIndex; $i++) {
        $requestedNthFieldName = $arrayToParse[$i];
        if (!isset($arIteratedData[$requestedNthFieldName])) {
            return null;
        }
        $arIteratedData = $arIteratedData[$requestedNthFieldName];
    }
    return $arIteratedData;
}
Пример #2
0
 /**
  * Sends notifications to IM.
  *
  * @param $fromUserID
  * @param $arRecipientsIDs
  * @param $message
  * @param int $taskID
  * @param null $message_email
  * @param array $arEventData
  * @return bool|null
  */
 public static function SendMessage($fromUserID, $arRecipientsIDs, $message, $taskID = 0, $message_email = null, $arEventData = array(), $taskAssignedTo = null)
 {
     if (!(IsModuleInstalled("im") && CModule::IncludeModule("im"))) {
         return false;
     }
     $message_email = is_null($message_email) ? $message : $message_email;
     if (!($fromUserID && $arRecipientsIDs && $message)) {
         return false;
     }
     CTaskAssert::assert(is_array($arEventData));
     $arEventData['fromUserID'] =& $fromUserID;
     $arEventData['arRecipientsIDs'] =& $arRecipientsIDs;
     $arEventData['message'] =& $message;
     $arEventData['message_email'] =& $message_email;
     foreach (GetModuleEvents('tasks', 'OnBeforeTaskNotificationSend', true) as $arEvent) {
         if (ExecuteModuleEventEx($arEvent, array($arEventData)) === false) {
             return false;
         }
     }
     $arSites = array();
     if (CModule::IncludeModule("extranet")) {
         $dbSite = CSite::GetList($by = "sort", $order = "desc", array("ACTIVE" => "Y"));
         while ($arSite = $dbSite->Fetch()) {
             $type = $arSite["ID"] == CExtranet::GetExtranetSiteID() ? "EXTRANET" : "INTRANET";
             if ($type === 'INTRANET' && isset($arSites['INTRANET']) && $arSite['DEF'] !== 'Y') {
                 // Don't overwrite INTRANET site data by not default site
                 continue;
             }
             $arSites[$type] = array('SITE_ID' => $arSite['ID'], "DIR" => strlen(trim($arSite["DIR"])) > 0 ? $arSite["DIR"] : "/", "SERVER_NAME" => strlen(trim($arSite["SERVER_NAME"])) > 0 ? $arSite["SERVER_NAME"] : COption::GetOptionString("main", "server_name", $_SERVER["HTTP_HOST"]));
         }
     }
     if (is_array($arRecipientsIDs) && count($arRecipientsIDs)) {
         $arRecipientsIDs = array_unique($arRecipientsIDs);
         $rsUser = CUser::GetList($by = 'ID', $order = 'ASC', array('ID' => implode('|', $arRecipientsIDs)), array('FIELDS' => array('ID')));
         while ($arUser = $rsUser->Fetch()) {
             $notifyEvent = 'manage';
             if ($taskAssignedTo !== null) {
                 if ($arUser['ID'] == $taskAssignedTo) {
                     $notifyEvent = 'task_assigned';
                 }
             }
             $pathToTask = CTaskNotifications::GetNotificationPath($arUser, $taskID, true, $arSites);
             $arMessageFields = array("TO_USER_ID" => $arUser['ID'], "FROM_USER_ID" => $fromUserID, "NOTIFY_TYPE" => IM_NOTIFY_FROM, "NOTIFY_MODULE" => "tasks", "NOTIFY_EVENT" => $notifyEvent, "NOTIFY_MESSAGE" => str_replace("#PATH_TO_TASK#", $pathToTask, $message), "NOTIFY_MESSAGE_OUT" => strip_tags(str_replace("#PATH_TO_TASK#", $pathToTask, $message_email)));
             CIMNotify::Add($arMessageFields);
         }
     }
     return null;
 }
Пример #3
0
 private static function managePerHitOptions($operation, $moduleId, $optionName, $value = null)
 {
     static $arOptions = array();
     $oName = $moduleId . '::' . $optionName;
     if (!array_key_exists($oName, $arOptions)) {
         $arOptions[$oName] = null;
     }
     $rc = null;
     if ($operation === 'read') {
         $rc = $arOptions[$oName];
     } elseif ($operation === 'write') {
         $arOptions[$oName] = $value;
     } else {
         CTaskAssert::assert(false);
     }
     return $rc;
 }
Пример #4
0
 public static function onAfterTimeManagerDayStart($arData)
 {
     if (!(isset($arData['USER_ID'], $arData['MODIFIED_BY']) && $arData['USER_ID'] > 0 && $arData['MODIFIED_BY'] > 0 && $arData['MODIFIED_BY'] == $arData['USER_ID'] && IsModuleInstalled("im") && CModule::IncludeModule("im"))) {
         return;
     }
     $recipientId = (int) $arData['USER_ID'];
     try {
         $tasksCounter = CTaskListCtrl::getMainCounterForUser($recipientId);
         if ($tasksCounter <= 0) {
             return;
         }
         /** @noinspection PhpDeprecationInspection */
         CIMNotify::Add(array('FROM_USER_ID' => 0, 'TO_USER_ID' => $recipientId, 'NOTIFY_MODULE' => 'tasks', 'NOTIFY_EVENT' => 'notice', 'NOTIFY_TYPE' => IM_NOTIFY_SYSTEM, 'NOTIFY_TAG' => 'TASKS|COUNTERS_NOTICE|' . $recipientId, 'MESSAGE' => CTasksTools::getMessagePlural($tasksCounter, 'TASKS_COUNTERS_NOTICE_CONTENT_V2', array('#TASKS_COUNT#' => $tasksCounter, '#HREF#' => self::getTasksListLink($recipientId))), 'TITLE' => GetMessage('TASKS_COUNTERS_NOTICE_TITLE')));
     } catch (Exception $e) {
         CTaskAssert::logWarning('[0xb83d6845] unexpected exception in CTaskCountersNotifier::onAfterTimeManagerDayStart()' . ', file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', code: ' . $e->getCode() . ', message: ' . $e->getMessage());
     }
 }
Пример #5
0
 /**
  * @param CTaskItemInterface $oTaskItem
  * @throws TasksException
  * @return array $arReturn with elements
  * 		<ul>
  * 		<li>$arReturn[0] - array of items
  * 		<li>$arReturn[1] - CDBResult
  * 		</ul>
  */
 public static function fetchList(CTaskItemInterface $oTaskItem, $arOrder = array(), $arFilter = array())
 {
     $arItems = array();
     CTaskAssert::assert($oTaskItem instanceof CTaskItemInterface);
     $taskId = (int) $oTaskItem->getId();
     // Ensure that we have read access for task
     $taskData = $oTaskItem->getData();
     try {
         list($arItemsData, $rsData) = static::fetchListFromDb($taskData, $arOrder, $arFilter);
     } catch (Exception $e) {
         throw new TasksException('Action failed', TasksException::TE_ACTION_FAILED_TO_BE_PROCESSED);
     }
     foreach ($arItemsData as $arItemData) {
         $arItems[] = self::constructWithPreloadedData($oTaskItem, $arItemData['ID'], $arItemData);
     }
     return array($arItems, $rsData);
 }
Пример #6
0
 public static function runRestMethod($executiveUserId, $methodName, $args, $navigation)
 {
     static $arManifest = null;
     static $arMethodsMetaInfo = null;
     if ($arManifest === null) {
         $arManifest = self::getManifest();
         $arMethodsMetaInfo = $arManifest['REST: available methods'];
     }
     // Check and parse params
     CTaskAssert::assert(isset($arMethodsMetaInfo[$methodName]));
     $arMethodMetaInfo = $arMethodsMetaInfo[$methodName];
     $argsParsed = CTaskRestService::_parseRestParams('ctasklogitem', $methodName, $args);
     $returnValue = null;
     if (isset($arMethodMetaInfo['staticMethod']) && $arMethodMetaInfo['staticMethod']) {
         if ($methodName === 'list') {
             $taskId = $argsParsed[0];
             $order = $argsParsed[1];
             $filter = $argsParsed[2];
             $oTaskItem = CTaskItem::getInstance($taskId, $executiveUserId);
             list($items, $rsData) = self::fetchList($oTaskItem, $order, $filter);
             $returnValue = array();
             foreach ($items as $item) {
                 $returnValue[] = $item->getData(false);
             }
         } else {
             $returnValue = call_user_func_array(array('self', $methodName), $argsParsed);
         }
     } else {
         $taskId = array_shift($argsParsed);
         $itemId = array_shift($argsParsed);
         $oTaskItem = CTaskItem::getInstance($taskId, $executiveUserId);
         $item = new self($oTaskItem, $itemId);
         $returnValue = call_user_func_array(array($item, $methodName), $argsParsed);
     }
     return array($returnValue, null);
 }
Пример #7
0
 private static function processUsersCounters($counterId, $operation, $arUsers, $delta)
 {
     if (!is_array($arUsers)) {
         CTaskAssert::logError('[0x9418f293] ');
         return;
     }
     $arUsers = array_unique($arUsers);
     if ($operation === self::OP_DECREMENT) {
         foreach ($arUsers as $userId) {
             $userId = (int) $userId;
             if ($userId < 1) {
                 CTaskAssert::logError('[0x8886cc18] ');
                 continue;
             }
             //$x = '[USER_ID= ' . $userId . '] ' . $counterId . '--';
             //soundex($x);
             CUserCounter::Decrement($userId, $counterId, '**', false, $delta);
         }
     } elseif ($operation === self::OP_INCREMENT) {
         foreach ($arUsers as $userId) {
             $userId = (int) $userId;
             if ($userId < 1) {
                 CTaskAssert::logError('[0x01f722e7] ');
                 continue;
             }
             //$x = '[USER_ID= ' . $userId . '] ' . $counterId . '+=' . $delta;
             //soundex($x);
             CUserCounter::Increment((int) $userId, $counterId, '**', false, $delta);
         }
     } else {
         CTaskAssert::logError('[0x0a5999d4] Invalid operation: ' . $operation);
     }
 }
Пример #8
0
                    }
                    $APPLICATION->IncludeComponent("bitrix:tasks.task.detail.parts", ".default", array('INNER_HTML' => $_POST['INNER_HTML'], 'MODE' => $_POST['MODE'], 'BLOCKS' => array($_POST['BLOCK']), 'IS_IFRAME' => $isIframe, 'PATH_TO_TEMPLATES_TEMPLATE' => $_POST['PATH_TO_TEMPLATES_TEMPLATE'], 'PATH_TO_USER_PROFILE' => $_POST['PATH_TO_USER_PROFILE'], 'PATH_TO_TASKS_TASK' => $_POST['PATH_TO_TASKS_TASK'], 'FIRE_ON_CHANGED_EVENT' => $_POST['FIRE_ON_CHANGED_EVENT'], 'NAME_TEMPLATE' => $nameTemplate, 'LOAD_TASK_DATA' => 'Y', 'TASK_ID' => (int) $_POST['TASK_ID']), null, array('HIDE_ICONS' => 'Y'));
                    break;
                default:
                    CTaskAssert::logError('[0x4fae6498] Unexpected $_POST[\'BLOCK\'] value: ' . $_POST['BLOCK']);
                    break;
            }
        } else {
            CTaskAssert::logError('[0x0907bb31] $_POST[\'BLOCK\'] expected, but not given');
        }
    } elseif ($action === 'render_comments') {
        CModule::IncludeModule('tasks');
        CModule::IncludeModule('forum');
        $permission = 'A';
        $oTask = CTaskItem::getInstanceFromPool($_POST['taskId'], $loggedInUserId);
        $arTask = $oTask->getData($bEscape = false);
        $arTaskUsers = CTasks::__GetSearchPermissions($arTask);
        if ($USER->CanAccess($arTaskUsers) === true || $USER->IsAdmin() || CTasksTools::IsPortalB24Admin()) {
            $permission = 'M';
        }
        $APPLICATION->RestartBuffer();
        header('Content-Type: text/html; charset=' . LANG_CHARSET);
        $APPLICATION->IncludeComponent("bitrix:forum.comments", "bitrix24", array("FORUM_ID" => $_POST['forumId'], "ENTITY_TYPE" => "TK", "ENTITY_ID" => $_POST['taskId'], "ENTITY_XML_ID" => "TASK_" . $_POST['taskId'], "URL_TEMPLATES_PROFILE_VIEW" => $_POST['PATH_TO_USER_PROFILE'], "MESSAGES_PER_PAGE" => $_POST['ITEM_DETAIL_COUNT'], "PAGE_NAVIGATION_TEMPLATE" => "arrows", "DATE_TIME_FORMAT" => CDatabase::DateFormatToPHP(FORMAT_DATETIME), "PATH_TO_SMILE" => $_POST['PATH_TO_FORUM_SMILE'], "EDITOR_CODE_DEFAULT" => "N", "SHOW_MODERATION" => "Y", "SHOW_AVATAR" => "Y", "SHOW_RATING" => $_POST['SHOW_RATING'], "RATING_TYPE" => $_POST['RATING_TYPE'], "SHOW_MINIMIZED" => "N", "USE_CAPTCHA" => "N", 'PREORDER' => 'N', "SHOW_LINK_TO_FORUM" => "N", "SHOW_SUBSCRIBE" => "N", "FILES_COUNT" => 10, "SHOW_WYSIWYG_EDITOR" => "Y", "AUTOSAVE" => true, "PERMISSION" => $permission, "NAME_TEMPLATE" => $_POST["NAME_TEMPLATE"], "MESSAGE_COUNT" => 3), null, array('HIDE_ICONS' => 'Y'));
        require $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/include/epilog_after.php';
        exit;
    } else {
        CTaskAssert::logError('[0x447f7b28] Unknown action: ' . $action);
    }
}
CMain::FinalActions();
// to make events work on bitrix24
Пример #9
0
 function Update($ID, $arFields, $arParams = array())
 {
     global $DB, $USER;
     $ID = intval($ID);
     if ($ID < 1) {
         return false;
     }
     $executiveUserId = null;
     if (isset($arParams['USER_ID'])) {
         $executiveUserId = (int) $arParams['USER_ID'];
     } elseif (is_object($USER) && method_exists($USER, 'getId')) {
         $executiveUserId = (int) $USER->getId();
     }
     if ($this->CheckFields($arFields, $ID)) {
         /** @noinspection PhpDeprecationInspection */
         $rsUpdatingLogItem = self::getByID($ID);
         if ($rsUpdatingLogItem && ($arUpdatingLogItem = $rsUpdatingLogItem->fetch())) {
             $taskId = $arUpdatingLogItem['TASK_ID'];
         } else {
             return false;
         }
         $curDuration = 0;
         $rsTask = CTasks::getList(array(), array('ID' => $taskId), array('ID', 'TIME_SPENT_IN_LOGS'));
         if ($rsTask && ($arTask = $rsTask->fetch())) {
             $curDuration = (int) $arTask['TIME_SPENT_IN_LOGS'];
         }
         unset($arFields["ID"]);
         $arBinds = array("COMMENT_TEXT" => $arFields["COMMENT_TEXT"]);
         // Maintance backward compatibility
         if (isset($arFields['MINUTES'], $arFields['SECONDS'])) {
             CTaskAssert::logError('[0x63038b4f] ');
             CTaskAssert::assert(false);
         }
         if (isset($arFields['SECONDS'])) {
             $arFields['MINUTES'] = (int) round($arFields['SECONDS'] / 60, 0);
         } elseif (isset($arFields['MINUTES'])) {
             $arFields['SECONDS'] = 60 * $arFields['MINUTES'];
         } else {
             CTaskAssert::logError('[0x14e5d0eb] ');
             CTaskAssert::assert(false);
         }
         foreach (GetModuleEvents('tasks', 'OnBeforeTaskElapsedTimeUpdate', true) as $arEvent) {
             if (ExecuteModuleEventEx($arEvent, array($ID, $arUpdatingLogItem, &$arFields)) === false) {
                 return false;
             }
         }
         // If time changed - set CTaskElapsedItem::SOURCE_MANUAL flag
         if ($arUpdatingLogItem['MINUTES'] != $arFields['MINUTES'] || $arUpdatingLogItem['SECONDS'] != $arFields['SECONDS']) {
             $arFields['SOURCE'] = CTaskElapsedItem::SOURCE_MANUAL;
         }
         $strUpdate = $DB->PrepareUpdate("b_tasks_elapsed_time", $arFields);
         $strSql = "UPDATE b_tasks_elapsed_time SET " . $strUpdate . " WHERE ID=" . $ID;
         $rc = $DB->QueryBind($strSql, $arBinds, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
         $occurAsUserId = CTasksTools::getOccurAsUserId();
         if (!$occurAsUserId) {
             $occurAsUserId = $executiveUserId ? $executiveUserId : 1;
         }
         $oLog = new CTaskLog();
         $oLog->Add(array('TASK_ID' => $taskId, 'USER_ID' => $occurAsUserId, '~CREATED_DATE' => $DB->currentTimeFunction(), 'FIELD' => 'TIME_SPENT_IN_LOGS', 'FROM_VALUE' => $curDuration, 'TO_VALUE' => $curDuration - (int) $arUpdatingLogItem['SECONDS'] + (int) $arFields['SECONDS']));
         foreach (GetModuleEvents('tasks', 'OnTaskElapsedTimeUpdate', true) as $arEvent) {
             ExecuteModuleEventEx($arEvent, array($ID, $arFields));
         }
         return $rc;
     }
     return false;
 }
Пример #10
0
		pulltext: '<?php 
echo GetMessageJS('MB_TASKS_TASKS_FILTER_PULLDOWN_PULL');
?>
',
		downtext: '<?php 
echo GetMessageJS('MB_TASKS_TASKS_FILTER_PULLDOWN_DOWN');
?>
',
		loadtext: '<?php 
echo GetMessageJS('MB_TASKS_TASKS_FILTER_PULLDOWN_LOADING');
?>
',
		action:   'RELOAD',
		callback: function() { app.reload(); }
	});
</script>
<?php 
$arResult = array();
$environmentCheck = isset($GLOBALS['APPLICATION']) && is_object($GLOBALS['APPLICATION']) && isset($GLOBALS['USER']) && is_object($GLOBALS['USER']) && isset($arParams) && is_array($arParams) && CModule::IncludeModule('tasks');
try {
    CTaskAssert::assert($environmentCheck);
    unset($environmentCheck);
    $arResult['USER_ID'] = (int) $_GET['USER_ID'];
    $oFilter = CTaskFilterCtrl::GetInstance($arResult['USER_ID']);
    $arResult['PRESETS_TREE'] = $oFilter->ListFilterPresets($bTreeMode = true);
    $arResult['CURRENT_PRESET_ID'] = $oFilter->GetSelectedFilterPresetId();
} catch (Exception $e) {
    return false;
}
$this->IncludeComponentTemplate();
return $arResult;
Пример #11
0
 private function checkColumns($columns)
 {
     $arAllowedColumnsIDs = array_keys(CTaskColumnList::get());
     CTaskAssert::assert(is_array($columns));
     foreach ($columns as &$columnData) {
         CTaskAssert::assert(isset($columnData['ID'], $columnData['WIDTH']) && count($columnData) == 2 && CTaskAssert::isLaxIntegers($columnData['ID'], $columnData['WIDTH']) && in_array($columnData['ID'], $arAllowedColumnsIDs) && $columnData['WIDTH'] >= 0);
     }
     unset($columnData);
 }
Пример #12
0
 private static function convertItemForExport($arItem)
 {
     static $arFields = null;
     $arResult = array();
     if ($arFields === null) {
         $arManifest = self::getManifest();
         $arFields = $arManifest['Fields'];
     }
     foreach ($arItem as $itemName => $itemData) {
         CTaskAssert::assert(strlen($itemName) > 2);
         if ($itemName === '::LOGIC') {
             $arResult[$itemName] = $itemData;
             continue;
         }
         if (substr($itemName, 0, 12) === '::SUBFILTER-') {
             $arResult[$itemName] = self::convertItemForExport($itemData);
             continue;
         }
         $value = $itemData;
         $itemName = ltrim($itemName);
         // Resolve operation code and cutoff operation prefix from item name
         $operation = null;
         foreach (self::$arOperationsMap as $operationCode => $operationPrefix) {
             $pattern = '/^' . preg_quote($operationPrefix) . '[A-Za-z]/';
             if (preg_match($pattern, $itemName)) {
                 $operation = $operationCode;
                 $itemName = substr($itemName, strlen($operationPrefix));
                 break;
             }
         }
         CTaskAssert::assert($operation !== null);
         // Process values for date fields
         if (isset($arFields[$itemName]['Type']) && $arFields[$itemName]['Type'] === self::TYPE_DATE) {
             $value = self::convertTimestampToDateString($operation, $value);
         }
         $arResult[] = array('field' => $itemName, 'operation' => $operation, 'value' => $value);
     }
     return $arResult;
     /*
     	data in:
     	$arFilter = array(
     		'::LOGIC' => 'AND',
     		'RESPONSIBLE_ID' => 1,
     		'::SUBFILTER-1' => array(
     			'::LOGIC' => 'OR',
     			'CREATED_BY' => 1,
     			'!=CREATED_BY' => 2
     		),
     		'::SUBFILTER-2' => array(
     			'::LOGIC' => 'AND',
     			'%TITLE' => 'some interesting substring',
     			'!%TITLE' => 'some not interesting substring'
     		)
     	);
     
     	data out:
     	array(
     		'::LOGIC' => 'AND',
     		array(
     			'field'     => 'RESPONSIBLE_ID',
     			'operation' => CTaskFilterCtrlInterface::OP_EQUAL,
     			'value'     => 1
     		),
     		'::SUBFILTER-1' => array(
     			'::LOGIC' => 'OR',
     			array(
     				'field'     => 'CREATED_BY',
     				'operation' => CTaskFilterCtrlInterface::OP_EQUAL,
     				'value'     => 1
     			),
     			array(
     				'field'     => 'CREATED_BY',
     				'operation' => CTaskFilterCtrlInterface::OP_NOT_EQUAL,
     				'value'     => 2
     			)
     		),
     		'::SUBFILTER-2' => array(
     			'::LOGIC' => 'AND',
     			array(
     				'field'     => 'TITLE',
     				'operation' => CTaskFilterCtrlInterface::OP_SUBSTRING,
     				'value'     => 1
     			),
     			array(
     				'field'     => 'TITLE',
     				'operation' => CTaskFilterCtrlInterface::OP_NOT_SUBSTRING,
     				'value'     => 2
     			)
     		)
     	)
     */
 }
 /**
  * This function resets all counters for all users and recounts them.
  * 
  * This function do work which IS NOT multi-thread safe.
  */
 public static function setup($step = self::STEP_BEGIN, $extraParam = null)
 {
     $nextStep = $nextStepDelay = $nextStepExtraParam = null;
     //$s = 'CTaskCountersProcessorInstaller::setup()';
     //soundex($s);
     $timeLimit = microtime(true) + 5;
     // give at least 5 seconds for work
     while (microtime(true) <= $timeLimit) {
         /** @noinspection PhpUnusedLocalVariableInspection */
         $nextStep = $nextStepDelay = $nextStepExtraParam = null;
         //soundex($step);
         if ($step === self::STEP_BEGIN) {
             self::setStage(self::STAGE_INSTALL_IN_PROGRESS);
             /** @noinspection PhpDynamicAsStaticMethodCallInspection */
             CAgent::RemoveAgent('CTaskCountersProcessor::agent();', 'tasks');
             /** @noinspection PhpDynamicAsStaticMethodCallInspection */
             CAgent::RemoveAgent('CTaskCountersProcessorInstaller::setup();', 'tasks');
             /** @noinspection PhpDynamicAsStaticMethodCallInspection */
             CAgent::RemoveAgent('CTaskCountersProcessorInstaller::setup("' . self::STEP_DROP_COUNTERS . '");', 'tasks');
             /** @noinspection PhpDynamicAsStaticMethodCallInspection */
             CAgent::RemoveAgent('CTaskCountersProcessorInstaller::setup("' . self::STEP_COUNT_NEW_FOR_RESPONSIBLES . '");', 'tasks');
             /** @noinspection PhpDynamicAsStaticMethodCallInspection */
             CAgent::RemoveAgent('CTaskCountersProcessorInstaller::setup("' . self::STEP_COUNT_NEW_FOR_ACCOMPLICES . '");', 'tasks');
             //CAgent::RemoveAgent('CTaskCountersProcessorInstaller::setup("' . self::STEP_COUNT_NEW_FOR_AUDITORS . '");', 'tasks');
             /** @noinspection PhpDynamicAsStaticMethodCallInspection */
             CAgent::RemoveAgent('CTaskCountersProcessorInstaller::setup("' . self::STEP_COUNT_WAIT_CTRL_FOR_ORIGINATORS . '");', 'tasks');
             /** @noinspection PhpDynamicAsStaticMethodCallInspection */
             CAgent::RemoveAgent('CTaskCountersProcessorInstaller::setup("' . self::STEP_COUNT_EXPIRED . '");', 'tasks');
             /** @noinspection PhpDynamicAsStaticMethodCallInspection */
             CAgent::RemoveAgent('CTaskCountersProcessorInstaller::setup("' . self::STEP_COUNT_WITHOUT_DEADLINES_MY . '");', 'tasks');
             /** @noinspection PhpDynamicAsStaticMethodCallInspection */
             CAgent::RemoveAgent('CTaskCountersProcessorInstaller::setup("' . self::STEP_COUNT_WITHOUT_DEADLINES_FOR_ORIGINATORS . '");', 'tasks');
             // defer for at min 130 seconds the next step,
             // because we must give time for CTaskCountersProcessor::agent()
             // to complete its work, if it was already started
             $nextStep = self::STEP_DROP_COUNTERS;
             $nextStepDelay = 130;
         } else {
             switch ($step) {
                 case self::STEP_DROP_COUNTERS:
                     // reset DEADLINE_COUNTED flags and all tasks counters for all users
                     self::reset();
                     $nextStep = self::STEP_COUNT_NEW_FOR_RESPONSIBLES;
                     break;
                 case self::STEP_COUNT_NEW_FOR_RESPONSIBLES:
                     self::recountCounters_MY_NEW($userId = '*');
                     // recount for all users
                     $nextStep = self::STEP_COUNT_NEW_FOR_ACCOMPLICES;
                     break;
                 case self::STEP_COUNT_NEW_FOR_ACCOMPLICES:
                     self::recountCounters_ACCOMPLICE_NEW($userId = '*');
                     // recount for all users
                     //$nextStep = self::STEP_COUNT_NEW_FOR_AUDITORS;
                     $nextStep = self::STEP_COUNT_WAIT_CTRL_FOR_ORIGINATORS;
                     break;
                 case self::STEP_COUNT_WAIT_CTRL_FOR_ORIGINATORS:
                     self::recountCounters_ORIGINATORS_WAIT_CTRL($userId = '*');
                     // recount for all users
                     $nextStep = self::STEP_COUNT_WITHOUT_DEADLINES_MY;
                     break;
                 case self::STEP_COUNT_WITHOUT_DEADLINES_MY:
                     self::recountCounters_MY_WITHOUT_DEADLINES($userId = '*');
                     // recount for all users
                     $nextStep = self::STEP_COUNT_WITHOUT_DEADLINES_FOR_ORIGINATORS;
                     break;
                 case self::STEP_COUNT_WITHOUT_DEADLINES_FOR_ORIGINATORS:
                     self::recountCounters_ORIGINATORS_WITHOUT_DEADLINES($userId = '*');
                     // recount for all users
                     $nextStep = self::STEP_COUNT_EXPIRED;
                     break;
                 case self::STEP_COUNT_EXPIRED:
                     $executionTimeLimit = mt_rand(1, 6);
                     // time limit in seconds
                     $itemsProcessed = CTaskCountersProcessor::countExpiredAndExpiredSoonTasks($executionTimeLimit);
                     // Some items processed?
                     if ($itemsProcessed > 0) {
                         // try again
                         $nextStep = self::STEP_COUNT_EXPIRED;
                         $nextStepDelay = 5;
                     } else {
                         /** @noinspection PhpDynamicAsStaticMethodCallInspection */
                         CAgent::AddAgent('CTaskCountersProcessor::agent();', 'tasks', 'N', 900);
                         // every 15 minutes
                         self::setStage(self::STAGE_INSTALL_COMPLETE);
                         CTaskCountersProcessorHomeostasis::onCalculationComplete();
                         $nextStep = null;
                         // the end
                     }
                     break;
                 default:
                     CTaskAssert::logError('[0xd7b90d6d] ');
                     $nextStep = null;
                     // the end
                     break;
             }
         }
         if ($nextStep === null) {
             break;
         }
         if ($nextStepDelay > 0) {
             break;
         }
         $step = $nextStep;
     }
     if ($nextStep !== null) {
         /** @noinspection PhpDeprecationInspection */
         $nextExecTimestamp = time() + CTasksTools::getTimeZoneOffset();
         if ($nextStepDelay !== null) {
             $nextExecTimestamp += $nextStepDelay;
         } else {
             $nextExecTimestamp += 5;
         }
         // delay for ~5 seconds due to probably DB and PHP server time desynchronization
         $delayedTime = ConvertTimeStamp($nextExecTimestamp, 'FULL');
         /** @noinspection PhpDynamicAsStaticMethodCallInspection */
         CAgent::AddAgent('CTaskCountersProcessorInstaller::setup("' . $nextStep . '");', 'tasks', 'N', 86400000, $delayedTime, "Y", $delayedTime, 13);
     }
     return "";
     // remove self from agents table
 }
Пример #14
0
                         CTaskAssert::assert(isset($_POST['movedColumnId'], $_POST['movedAfterColumnId'], $_POST['columnContextId']));
                         $loggedInUserId = $USER->getId();
                         $movedColumnId = (int) $_POST['movedColumnId'];
                         $movedAfterColumnId = (int) $_POST['movedAfterColumnId'];
                         $columnContextId = (int) $_POST['columnContextId'];
                         $knownColumnsIds = array_keys(CTaskColumnList::get());
                         CTaskAssert::assert($loggedInUserId >= 1);
                         CTaskAssert::assert(in_array($movedColumnId, $knownColumnsIds));
                         CTaskAssert::assert($movedAfterColumnId == 0 || in_array($movedAfterColumnId, $knownColumnsIds));
                         CTaskAssert::assert(in_array($columnContextId, CTaskColumnContext::get()));
                         $oPresetManager = CTaskColumnPresetManager::getInstance($loggedInUserId, $columnContextId);
                         $oColumnManager = new CTaskColumnManager($oPresetManager);
                         $oColumnManager->moveColumnAfter($movedColumnId, $movedAfterColumnId);
                     } else {
                         if ($_POST['mode'] === 'groupAction') {
                             CTaskAssert::assert(isset($_POST['action']));
                         }
                     }
                 }
             }
         }
     }
 } catch (Exception $e) {
     if ($jsonReply === null) {
         $jsonReply = array('status' => 'failure');
     }
 }
 if ($jsonReply !== null) {
     $APPLICATION->RestartBuffer();
     header('Content-Type: application/x-javascript; charset=' . LANG_CHARSET);
     echo CUtil::PhpToJsObject($jsonReply);
Пример #15
0
 private function __construct($userId)
 {
     CTaskAssert::assertLaxIntegers($userId);
     CTaskAssert::assert($userId > 0);
     $this->userId = (int) $userId;
 }
Пример #16
0
                        // ka-boom!
                        $templateInstance = new CTaskTemplates();
                        if ($templateInstance->Delete($templateId)) {
                            ++$processedItems;
                        } else {
                            ++$notProcessedItems;
                        }
                    }
                    break;
                default:
                    CTaskAssert::logError('[0x8a1747a5] unknown subaction: ' . $_POST['subaction']);
                    break;
            }
            break;
        default:
            CTaskAssert::logError('[0x8b300a99] unknown action: ' . $_POST['action']);
            break;
    }
    LocalRedirect($APPLICATION->GetCurPageParam("", array("sessid")));
}
$arParams["TASK_VAR"] = trim($arParams["TASK_VAR"]);
if (strlen($arParams["TASK_VAR"]) <= 0) {
    $arParams["TASK_VAR"] = "task_id";
}
$arParams["GROUP_VAR"] = trim($arParams["GROUP_VAR"]);
if (strlen($arParams["GROUP_VAR"]) <= 0) {
    $arParams["GROUP_VAR"] = "group_id";
}
$arParams["ACTION_VAR"] = trim($arParams["ACTION_VAR"]);
if (strlen($arParams["ACTION_VAR"]) <= 0) {
    $arParams["ACTION_VAR"] = "action";
Пример #17
0
                             }
                         }
                     }
                 }
                 if (!isset($arFileds['ID'])) {
                     $arFields['ID'] = $postId;
                 }
                 $arFields['~ID'] = $arFields['ID'];
                 $arFields['~TITLE'] = $arFields['TITLE'];
                 $arFields['~SORT_INDEX'] = $arFields['SORT_INDEX'];
                 $arFields['~IS_COMPLETE'] = $arFields['IS_COMPLETE'];
                 $arFields['TITLE'] = htmlspecialcharsbx($arFields['~TITLE']);
                 $arChecklistItems[] = $arFields;
             } catch (Exception $e) {
                 $arTaskData = $oTask->getData(false);
                 CTaskAssert::logError('[0x05b70569] Can\'t create checklist item, exception $e->getCode() = ' . $e->getCode() . ', file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', data: ' . serialize(array('LOGGED_USER_ID' => $USER->getId(), 'TASK_ID' => $arTaskData['ID'], 'CREATED_BY' => $arTaskData['CREATED_BY'], 'RESPONSIBLE_ID' => $arTaskData['RESPONSIBLE_ID'], 'ACCOMPLICES' => $arTaskData['ACCOMPLICES'], 'AUDITORS' => $arTaskData['AUDITORS'], 'ALLOWED_ACTIONS' => $oTask->getAllowedActions(true))) . '___END OF DATA');
             }
         }
         if ($arParams['TASK_ID'] > 0 && $arParams['MODE'] === 'JUST AFTER TASK EDITED') {
             $arItemsToRemove = array_diff($arChecklistItemsInDbIds, $arChecklistItemsInPostIds);
             if (is_array($arItemsToRemove) && !empty($arItemsToRemove)) {
                 foreach ($arChecklistItemsInDb as $oChecklistItem) {
                     if (in_array($oChecklistItem->getId(), $arItemsToRemove)) {
                         $oChecklistItem->delete();
                     }
                 }
             }
         }
     }
 }
 return $arChecklistItems;
Пример #18
0
 private static function resolveTaskCategoryName($categoryId)
 {
     static $arMap = null;
     $categoryId = (int) $categoryId;
     if ($arMap === null) {
         $arMap = array(self::VIEW_TASK_CATEGORY_ALL => GetMessage('TASKS_LIST_CTRL_CATEGORY_ALL'), self::VIEW_TASK_CATEGORY_NEW => GetMessage('TASKS_LIST_CTRL_CATEGORY_NEW'), self::VIEW_TASK_CATEGORY_IN_PROGRESS => GetMessage('TASKS_LIST_CTRL_CATEGORY_IN_PROGRESS'), self::VIEW_TASK_CATEGORY_COMPLETED => GetMessage('TASKS_LIST_CTRL_CATEGORY_COMPLETED'), self::VIEW_TASK_CATEGORY_DEFERRED => GetMessage('TASKS_LIST_CTRL_CATEGORY_DEFERRED'), self::VIEW_TASK_CATEGORY_EXPIRED => GetMessage('TASKS_LIST_CTRL_CATEGORY_EXPIRED'), self::VIEW_TASK_CATEGORY_EXPIRED_CANDIDATES => GetMessage('TASKS_LIST_CTRL_CATEGORY_EXPIRED_CANDIDATES'), self::VIEW_TASK_CATEGORY_ATTENTION => GetMessage('TASKS_LIST_CTRL_CATEGORY_ATTENTION'), self::VIEW_TASK_CATEGORY_WAIT_CTRL => GetMessage('TASKS_LIST_CTRL_CATEGORY_WAIT_CTRL'), self::VIEW_TASK_CATEGORY_WO_DEADLINE => GetMessage('TASKS_LIST_CTRL_CATEGORY_WO_DEADLINE'));
     }
     if (isset($arMap[$categoryId])) {
         return $arMap[$categoryId];
     } else {
         CTaskAssert::logError('[0xa1bd9ec0] ');
         return '???';
     }
 }
Пример #19
0
                    case 'sC':
                        // set category
                        $oListState->setTaskCategory($value);
                        break;
                    case 'eS':
                        // enable submode
                        $oListState->switchOnSubmode($value);
                        break;
                    case 'dS':
                        // disable submode
                        $oListState->switchOffSubmode($value);
                        break;
                }
                $oListState->saveState();
            } catch (TasksException $e) {
                CTaskAssert::logError('[0x523d4e28] : $switchStateTo = ' . $switchStateTo . ' (' . $value . ');' . ' cur user role: ' . $oListState->getUserRole() . ' serialize($arSwitchStateTo) = ' . serialize($arSwitchStateTo));
                // wrong user input, nothing to do here
            }
        }
    }
}
$arResult['VIEW_STATE'] = $oListState->getState();
$oListCtrl = CTaskListCtrl::getInstance($arParams['USER_ID']);
$oListCtrl->useState($oListState);
if ($arParams["GROUP_ID"] > 0) {
    $oListCtrl->setFilterByGroupId((int) $arParams["GROUP_ID"]);
} else {
    $oListCtrl->setFilterByGroupId(null);
}
// There is backward compatibility code:
if (!(isset($_GET['VIEW']) || isset($arParams['VIEW_MODE']))) {
Пример #20
0
 private static function getOrderSql($by, $order, $default_order, $nullable = true)
 {
     global $DBType;
     static $dbtype = null;
     if ($dbtype === null) {
         $dbtype = strtolower($DBType);
     }
     switch ($dbtype) {
         case 'mysql':
             return self::getOrderSql_mysql($by, $order, $default_order, $nullable = true);
             break;
         case 'mssql':
             return self::getOrderSql_mssql($by, $order, $default_order, $nullable = true);
             break;
         case 'oracle':
             return self::getOrderSql_oracle($by, $order, $default_order, $nullable = true);
             break;
         default:
             CTaskAssert::log('unknown DB type: ' . $dbtype, CTaskAssert::ELL_ERROR);
             return ' ';
             break;
     }
 }
Пример #21
0
 /**
  * @param $userId
  * @return array|bool array with keys TASK_ID, USER_ID, TIMER_STARTED_AT, TIMER_ACCUMULATOR,
  * or false on error
  */
 public static function stop($userId)
 {
     global $DB;
     $ts = time();
     if ($ts < 1) {
         CTaskAssert::logError('[0x03ad8b00] current unix timestamp is in past, check system time');
         CTaskAssert::assert(false);
     }
     $arData = self::get($userId);
     if ($arData !== false && ($arData['TIMER_STARTED_AT'] != 0 || $arData['TIMER_ACCUMULATOR'] != 0)) {
         $DB->query("UPDATE b_tasks_timer \n\t\t\t\tSET TIMER_ACCUMULATOR = 0, TIMER_STARTED_AT = 0\n\t\t\t\tWHERE\n\t\t\t\t\tUSER_ID = " . (int) $userId . "\n\t\t\t\t\tAND TASK_ID = " . (int) $arData['TASK_ID']);
         if ($arData['TIMER_STARTED_AT'] > 0 && $ts > $arData['TIMER_STARTED_AT']) {
             $arData['TIMER_ACCUMULATOR'] += $ts - $arData['TIMER_STARTED_AT'];
         }
         return $arData;
     } else {
         return false;
     }
 }
Пример #22
0
 public static function onEventFilter($arParams, $arHandler)
 {
     if (!isset($arHandler['EVENT_NAME'])) {
         $arHandler['EVENT_NAME'] = '$arHandler[\'EVENT_NAME\'] is not set';
     }
     $entityType = (string) array_shift($arParams);
     $taskId = (int) array_shift($arParams);
     $parameters = array_shift($arParams);
     $arEventFields = array('FIELDS_BEFORE' => 'undefined', 'FIELDS_AFTER' => 'undefined', 'IS_ACCESSIBLE_BEFORE' => 'undefined', 'IS_ACCESSIBLE_AFTER' => 'undefined');
     CTaskAssert::assert($taskId >= 1);
     // 'TK' is our entity type
     if ($entityType !== 'TK') {
         return;
     }
     if (empty($parameters["MESSAGE_ID"])) {
         return;
     }
     switch (strtolower($arHandler['EVENT_NAME'])) {
         case 'ontaskcommentadd':
             $arEventFields['FIELDS_BEFORE'] = 'undefined';
             $arEventFields['FIELDS_AFTER'] = array('ID' => $parameters["MESSAGE_ID"], 'TASK_ID' => $taskId);
             $arEventFields['IS_ACCESSIBLE_BEFORE'] = 'N';
             $arEventFields['IS_ACCESSIBLE_AFTER'] = 'undefined';
             break;
         case 'ontaskcommentupdate':
             $arEventFields['FIELDS_BEFORE'] = array('ID' => $parameters["MESSAGE_ID"], 'TASK_ID' => $taskId);
             $arEventFields['FIELDS_AFTER'] = array('ID' => $parameters["MESSAGE_ID"], 'TASK_ID' => $taskId, 'ACTION' => $parameters["ACTION"]);
             $arEventFields['IS_ACCESSIBLE_BEFORE'] = 'undefined';
             $arEventFields['IS_ACCESSIBLE_AFTER'] = 'undefined';
             break;
         default:
             throw new Exception('tasks\' RPC event handler: onEventFilter: ' . 'not allowed $arHandler[\'EVENT_NAME\']: ' . $arHandler['EVENT_NAME']);
             break;
     }
     return $arEventFields;
 }
Пример #23
0
 /**
  * @deprecated
  */
 public static function runRestMethod($executiveUserId, $methodName, $args, $navigation)
 {
     static $arManifest = null;
     static $arMethodsMetaInfo = null;
     if ($arManifest === null) {
         $arManifest = self::getManifest();
         $arMethodsMetaInfo = $arManifest['REST: available methods'];
     }
     // Check and parse params
     CTaskAssert::assert(isset($arMethodsMetaInfo[$methodName]));
     $arMethodMetaInfo = $arMethodsMetaInfo[$methodName];
     $argsParsed = CTaskRestService::_parseRestParams('ctaskcomments', $methodName, $args);
     $returnValue = null;
     if (isset($arMethodMetaInfo['staticMethod']) && $arMethodMetaInfo['staticMethod']) {
         if ($methodName === 'add') {
             $occurAsUserId = CTasksTools::getOccurAsUserId();
             if (!$occurAsUserId) {
                 $occurAsUserId = $executiveUserId;
             }
             $taskId = $argsParsed[0];
             $commentText = $argsParsed[1];
             $commentAuthorId = $occurAsUserId;
             $returnValue = self::add($taskId, $commentAuthorId, $commentText);
         }
     } else {
         $taskId = array_shift($argsParsed);
         $oTask = self::getInstanceFromPool($taskId, $executiveUserId);
         $returnValue = call_user_func_array(array($oTask, $methodName), $argsParsed);
     }
     return array($returnValue, null);
 }
Пример #24
0
            $oFilter = CTaskFilterCtrl::getInstance($loggedInUser);
            $newPresetId = $oFilter->importFilterDataFromJs($_POST['presetData'], $mode, $presetId);
            $arReply['newPresetId'] = $newPresetId;
        } catch (Exception $e) {
            $status = 'fail';
        }
        break;
    case 'removePreset':
        try {
            CTaskAssert::assert(isset($_POST['presetId']) && $_POST['presetId'] > 0);
            CTaskAssert::assertLaxIntegers($_POST['presetId']);
            $oFilter = CTaskFilterCtrl::getInstance($loggedInUser);
            $arPresetDefinition = $oFilter->removePreset($_POST['presetId']);
            if ($arPresetDefinition !== false) {
                $arReply = array('removedPresetId' => (int) $_POST['presetId']);
            } else {
                $status = 'fail';
            }
        } catch (Exception $e) {
            $status = 'fail';
        }
        break;
    default:
        CTaskAssert::assert(false);
        break;
}
$APPLICATION->RestartBuffer();
header('Content-Type: application/x-javascript; charset=' . LANG_CHARSET);
echo CUtil::PhpToJsObject(array('status' => $status, 'reply' => $arReply));
CMain::FinalActions();
// to make events work on bitrix24
Пример #25
0
 function Update($ID, $arFields, $arParams = array())
 {
     global $DB, $USER, $USER_FIELD_MANAGER;
     $ID = intval($ID);
     if ($ID < 1) {
         return false;
     }
     $bCheckFilesPermissions = false;
     if (isset($arParams['CHECK_RIGHTS_ON_FILES']) && ($arParams['CHECK_RIGHTS_ON_FILES'] === true || $arParams['CHECK_RIGHTS_ON_FILES'] === 'Y')) {
         CTaskAssert::assert(isset($arParams['USER_ID']) && CTaskAssert::isLaxIntegers($arParams['USER_ID']) && $arParams['USER_ID'] > 0);
         $bCheckFilesPermissions = true;
     }
     $arParamsForCheckFields = array('CHECK_RIGHTS_ON_FILES' => $bCheckFilesPermissions);
     if (isset($arParams['USER_ID'])) {
         $arParamsForCheckFields['USER_ID'] = $arParams['USER_ID'];
     }
     // We need understand, does REPLICATE_PARAMS changed
     $rsCurData = self::GetByID($ID);
     $arCurData = $rsCurData->Fetch();
     $this->currentData = $arCurData;
     if (intval($arCurData['BASE_TEMPLATE_ID']) > 0) {
         unset($arFields['REPLICATE']);
         // ... you cannot set replicate params
         unset($arFields['PARENT_ID']);
         // ... and base task
         $isReplicateParamsChanged = false;
     } else {
         $isReplicateParamsChanged = isset($arFields['REPLICATE']) && $arCurData['REPLICATE'] !== $arFields['REPLICATE'] || isset($arFields['REPLICATE_PARAMS']) && $arCurData['REPLICATE_PARAMS'] !== $arFields['REPLICATE_PARAMS'];
     }
     if ($userID === null) {
         $userID = is_object($USER) ? intval($USER->GetID()) : 1;
     }
     if ($this->CheckFields($arFields, $ID, $arParamsForCheckFields)) {
         if ($USER_FIELD_MANAGER->CheckFields("TASKS_TASK_TEMPLATE", $ID, $arFields)) {
             unset($arFields['ID']);
             $arBinds = array('DESCRIPTION' => $arFields['DESCRIPTION'], 'REPLICATE_PARAMS' => $arFields['REPLICATE_PARAMS'], 'ACCOMPLICES' => $arFields['ACCOMPLICES'], 'AUDITORS' => $arFields['AUDITORS'], 'FILES' => $arFields['FILES'], 'TAGS' => $arFields['TAGS'], 'DEPENDS_ON' => $arFields['DEPENDS_ON']);
             $strUpdate = $DB->PrepareUpdate('b_tasks_template', $arFields, 'tasks');
             if ((string) $strUpdate !== '') {
                 $strSql = "UPDATE b_tasks_template SET " . $strUpdate . " WHERE ID=" . $ID;
                 $DB->QueryBind($strSql, $arBinds, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
             }
             if (isset($arFields['FILES'])) {
                 CTaskFiles::removeTemporaryStatusForFiles(unserialize($arFields['FILES']), $arParams['USER_ID']);
             }
             $USER_FIELD_MANAGER->Update("TASKS_TASK_TEMPLATE", $ID, $arFields, $userID);
             // update template tree, if required
             if (isset($arFields['BASE_TEMPLATE_ID'])) {
                 try {
                     Template\DependencyTable::link($ID, intval($arFields['BASE_TEMPLATE_ID']), array('CREATE_PARENT_NODE_ON_NOTFOUND' => true));
                 } catch (\Bitrix\Tasks\DB\Tree\LinkExistsException $e) {
                 }
             }
             if ($isReplicateParamsChanged) {
                 // Firstly, remove all agents for this template
                 /** @noinspection PhpDynamicAsStaticMethodCallInspection */
                 CAgent::RemoveAgent('CTasks::RepeatTaskByTemplateId(' . $ID . ');', 'tasks');
                 /** @noinspection PhpDynamicAsStaticMethodCallInspection */
                 CAgent::RemoveAgent('CTasks::RepeatTaskByTemplateId(' . $ID . ', 0);', 'tasks');
                 /** @noinspection PhpDynamicAsStaticMethodCallInspection */
                 CAgent::RemoveAgent('CTasks::RepeatTaskByTemplateId(' . $ID . ', 1);', 'tasks');
                 // Set up new agent
                 if ($arFields['REPLICATE'] === 'Y') {
                     $nextTime = CTasks::GetNextTime(unserialize($arFields['REPLICATE_PARAMS']));
                     if ($nextTime) {
                         CTimeZone::Disable();
                         /** @noinspection PhpDynamicAsStaticMethodCallInspection */
                         CAgent::AddAgent('CTasks::RepeatTaskByTemplateId(' . $ID . ', 0);', 'tasks', 'N', 86400, $nextTime, 'Y', $nextTime);
                         CTimeZone::Enable();
                     }
                 }
             }
             return true;
         }
     }
     return false;
 }
Пример #26
0
 /**
  * This function is for internal use only, not a part of public API
  *
  * @access private
  */
 public static function _parseRestParams($className, $methodName, $inArgs)
 {
     CTaskAssert::assert(is_array($inArgs) && isset(self::$arMethodsMetaInfo[$className][$methodName]));
     $arMethodMetaInfo = self::$arMethodsMetaInfo[$className][$methodName];
     $arAllowedParams = $arMethodMetaInfo['params'];
     $mandatoryParamsCount = $arMethodMetaInfo['mandatoryParamsCount'];
     $arDateFields = array();
     if (isset(self::$arManifests[$className]['REST: date fields'])) {
         $arDateFields = self::$arManifests[$className]['REST: date fields'];
     }
     $outArgs = array();
     foreach ($arAllowedParams as $paramIndex => $paramMetaInfo) {
         // No more params given?
         if (!array_key_exists($paramIndex, $inArgs)) {
             // Set default value, if need
             if (array_key_exists('defaultValue', $paramMetaInfo)) {
                 $inArgs[$paramIndex] = $paramMetaInfo['defaultValue'];
             } elseif ($paramIndex < $mandatoryParamsCount) {
                 throw new TasksException('Param #' . $paramIndex . ' (' . $paramMetaInfo['description'] . ')' . ' expected by method ' . $className . '::' . $methodName . '(), but not given.', TasksException::TE_WRONG_ARGUMENTS);
             } else {
                 break;
             }
             // no more params to be processed
         }
         // for "galvanic isolation" of input/output
         $paramValue = $inArgs[$paramIndex];
         // Check param type
         /** @noinspection PhpUnusedLocalVariableInspection */
         $isCorrectValue = false;
         switch ($paramMetaInfo['type']) {
             case 'boolean':
                 if ($paramValue === '0' || $paramValue === 0) {
                     $paramValue = false;
                 } elseif ($paramValue === '1' || $paramValue === 1) {
                     $paramValue = true;
                 }
                 $isCorrectValue = is_bool($paramValue);
                 break;
             case 'array':
                 $isCorrectValue = is_array($paramValue);
                 break;
             case 'string':
                 $isCorrectValue = is_string($paramValue);
                 break;
             case 'integer':
                 $isCorrectValue = CTaskAssert::isLaxIntegers($paramValue);
                 break;
             default:
                 throw new TasksException('Internal error: unknown param type: ' . $paramMetaInfo['type'], TasksException::TE_UNKNOWN_ERROR);
                 break;
         }
         if (!$isCorrectValue) {
             throw new TasksException('Param #' . $paramIndex . ' (' . $paramMetaInfo['description'] . ')' . ' for method ' . $className . '::' . $methodName . '()' . ' expected to be of type "' . $paramMetaInfo['type'] . '",' . ' but given something else.', TasksException::TE_WRONG_ARGUMENTS);
         }
         // add legal aggregated columns in keys & values array
         if (is_array($paramMetaInfo['allowedAggregations'])) {
             // for keys
             if (is_array($paramMetaInfo['allowedKeysInAggregation'])) {
                 $fields = $paramMetaInfo['allowedKeysInAggregation'];
             } else {
                 $fields = $paramMetaInfo['allowedKeys'];
             }
             if (is_array($fields)) {
                 $aggrCombos = static::getAllowedAggregateCombos($paramMetaInfo['allowedAggregations'], $fields);
                 $paramMetaInfo['allowedKeys'] = array_merge($paramMetaInfo['allowedKeys'], $aggrCombos);
             }
             // for values
             if (is_array($paramMetaInfo['allowedValuesInAggregation'])) {
                 $fields = $paramMetaInfo['allowedValuesInAggregation'];
             } else {
                 $fields = $paramMetaInfo['allowedValues'];
             }
             if (is_array($fields)) {
                 $aggrCombos = static::getAllowedAggregateCombos($paramMetaInfo['allowedAggregations'], $fields);
                 $paramMetaInfo['allowedValues'] = array_merge($paramMetaInfo['allowedValues'], $aggrCombos);
             }
         }
         if (isset($paramMetaInfo['allowedKeys'])) {
             CTaskAssert::assert(is_array($paramValue));
             // ensure that $paramValue is array
             /** @var $paramValue array */
             foreach (array_keys($paramValue) as $key) {
                 // a little fix to be able to pass an empty array in order to "skip" argument
                 if ((string) $key == '0' && $paramValue[$key] == '') {
                     unset($paramValue[$key]);
                     continue;
                 }
                 if (isset($paramMetaInfo['allowedKeyPrefixes'])) {
                     $keyWoPrefix = str_replace($paramMetaInfo['allowedKeyPrefixes'], '', $key);
                 } else {
                     $keyWoPrefix = $key;
                 }
                 if (!in_array((string) $keyWoPrefix, $paramMetaInfo['allowedKeys'], true)) {
                     throw new TasksException('Param #' . $paramIndex . ' (' . $paramMetaInfo['description'] . ')' . ' for method ' . $className . '::' . $methodName . '()' . ' must not contain key "' . $key . '".', TasksException::TE_WRONG_ARGUMENTS);
                 }
                 // Additionally convert datetime fields from ISO 8601
                 if (in_array((string) $keyWoPrefix, $arDateFields, true) && !in_array($paramValue[$key], array('asc', 'desc'))) {
                     $paramValue[$key] = (string) CRestUtil::unConvertDateTime($paramValue[$key]);
                 }
             }
         }
         if (isset($paramMetaInfo['allowedValues'])) {
             CTaskAssert::assert(is_array($paramValue));
             foreach ($paramValue as $value) {
                 if ($value !== null && !is_bool($value)) {
                     $value = (string) $value;
                 }
                 if (!in_array($value, $paramMetaInfo['allowedValues'], true)) {
                     throw new TasksException('Param #' . $paramIndex . ' (' . $paramMetaInfo['description'] . ')' . ' for method ' . $className . '::' . $methodName . '()' . ' must not contain value "' . $value . '".', TasksException::TE_WRONG_ARGUMENTS);
                 }
             }
         }
         // "galvanic isolation" of input/output
         $outArgs[] = $paramValue;
     }
     if (count($inArgs) > count($arAllowedParams)) {
         throw new TasksException('Too much params(' . count($inArgs) . ') given for method ' . $className . '::' . $methodName . '()' . ', but expected not more than ' . count($arAllowedParams) . '.', TasksException::TE_WRONG_ARGUMENTS);
     }
     return $outArgs;
 }
Пример #27
0
 /**
  * This method is only for rest purposes
  * 
  * @access private
  */
 public static function runRestMethod($executiveUserId, $methodName, $args, $navigation)
 {
     static $arManifest = null;
     static $arMethodsMetaInfo = null;
     $rsData = null;
     if ($arManifest === null) {
         $arManifest = self::getManifest();
         $arMethodsMetaInfo = $arManifest['REST: available methods'];
     }
     // Check and parse params
     CTaskAssert::assert(isset($arMethodsMetaInfo[$methodName]));
     $arMethodMetaInfo = $arMethodsMetaInfo[$methodName];
     $argsParsed = CTaskRestService::_parseRestParams('ctaskitem', $methodName, $args);
     $runAs = $methodName;
     if (isset($arMethodsMetaInfo[$methodName]['runAs']) && (string) $arMethodsMetaInfo[$methodName]['runAs'] != '') {
         $runAs = $arMethodsMetaInfo[$methodName]['runAs'];
     }
     $returnValue = null;
     if (isset($arMethodMetaInfo['staticMethod']) && $arMethodMetaInfo['staticMethod']) {
         if ($methodName === 'add') {
             $argsParsed[] = $executiveUserId;
             /** @var CTaskItem $oTaskItem */
             $oTaskItem = call_user_func_array(array('self', $methodName), $argsParsed);
             $taskId = (int) $oTaskItem->getId();
             $returnValue = $taskId;
             self::cacheInstanceInPool($taskId, $executiveUserId, $oTaskItem);
         } elseif ($methodName === 'getlist' || $methodName === 'list') {
             array_unshift($argsParsed, $executiveUserId);
             // we need to fill default values up to $arParams (4th) argument
             while (!array_key_exists(3, $argsParsed)) {
                 $argsParsed[] = array();
             }
             if ($navigation['iNumPage'] > 1) {
                 $argsParsed[3]['NAV_PARAMS'] = array('nPageSize' => CTaskRestService::TASKS_LIMIT_PAGE_SIZE, 'iNumPage' => (int) $navigation['iNumPage']);
             } else {
                 if (isset($argsParsed[3]['NAV_PARAMS'])) {
                     if (isset($argsParsed[3]['NAV_PARAMS']['nPageTop'])) {
                         $argsParsed[3]['NAV_PARAMS']['nPageTop'] = min(CTaskRestService::TASKS_LIMIT_TOP_COUNT, (int) $argsParsed[3]['NAV_PARAMS']['nPageTop']);
                     }
                     if (isset($argsParsed[3]['NAV_PARAMS']['nPageSize'])) {
                         $argsParsed[3]['NAV_PARAMS']['nPageSize'] = min(CTaskRestService::TASKS_LIMIT_PAGE_SIZE, (int) $argsParsed[3]['NAV_PARAMS']['nPageSize']);
                     }
                     if (!isset($argsParsed[3]['NAV_PARAMS']['nPageTop']) && !isset($argsParsed[3]['NAV_PARAMS']['nPageSize'])) {
                         $argsParsed[3]['NAV_PARAMS'] = array('nPageSize' => CTaskRestService::TASKS_LIMIT_PAGE_SIZE, 'iNumPage' => 1);
                     }
                 } else {
                     $argsParsed[3]['NAV_PARAMS'] = array('nPageSize' => CTaskRestService::TASKS_LIMIT_PAGE_SIZE, 'iNumPage' => 1);
                 }
             }
             /** @var CTaskItem[] $oTaskItems */
             /** @noinspection PhpUnusedLocalVariableInspection */
             list($oTaskItems, $rsData) = call_user_func_array(array('self', 'fetchList'), $argsParsed);
             $returnValue = array();
             foreach ($oTaskItems as $oTaskItem) {
                 $arTaskData = $oTaskItem->getData(false);
                 $arTaskData['ALLOWED_ACTIONS'] = $oTaskItem->getAllowedActionsAsStrings();
                 if (isset($argsParsed[3])) {
                     if (isset($argsParsed[3]['LOAD_TAGS']) && ($argsParsed[3]['LOAD_TAGS'] == 1 || $argsParsed[3]['LOAD_TAGS'] == 'Y')) {
                         $arTaskData['TAGS'] = $oTaskItem->getTags();
                     }
                 }
                 $returnValue[] = $arTaskData;
             }
         } else {
             $returnValue = call_user_func_array(array('self', $runAs), $argsParsed);
         }
     } else {
         $taskId = array_shift($argsParsed);
         $oTask = self::getInstanceFromPool($taskId, $executiveUserId);
         $returnValue = call_user_func_array(array($oTask, $runAs), $argsParsed);
     }
     return array($returnValue, $rsData);
 }
Пример #28
0
 public static function runRestMethod($executiveUserId, $methodName, $args, $navigation)
 {
     CTaskAssert::assert($methodName === 'getcurrenttaskslist');
     // Check and parse params
     $argsParsed = CTaskRestService::_parseRestParams('ctaskplannermaintance', $methodName, $args);
     $arTasksIds = call_user_func_array(array('self', 'getcurrenttaskslist'), $argsParsed);
     return array($arTasksIds, null);
 }
 /**
  * Checks for broken counters.
  * Expirity counter is broken if it is < 0, or if it is more than tasks count in list of expired tasks
  * Other counters is broken if it is < 0, or if it is != tasks count in list of respective tasks
  *
  * Method is called inside CTask::GetList() to perform recounting of broken counters.
  * 
  * @param $arFilter Filter was used in GetList() call
  * @param $tasksCountInList Number of records returned by GetList() call
  */
 public static function onTaskGetList($arFilter, $tasksCountInList)
 {
     if (!CTaskCountersProcessorInstaller::isInstallComplete()) {
         return;
     }
     // Is there our marker?
     if (!(array_key_exists('::MARKERS', $arFilter) && array_key_exists(self::MARKER_ID, $arFilter['::MARKERS']) && $tasksCountInList !== null)) {
         return;
     }
     $tasksCountInList = (int) $tasksCountInList;
     $counterOwnerUserId = $arFilter['::MARKERS'][self::MARKER_ID]['userId'];
     $counterId = $arFilter['::MARKERS'][self::MARKER_ID]['counterId'];
     $counterValue = (int) CUserCounter::GetValue($counterOwnerUserId, $counterId, $site_id = '**');
     if (in_array($counterId, array(CTaskCountersProcessor::COUNTER_TASKS_MY_EXPIRED, CTaskCountersProcessor::COUNTER_TASKS_ACCOMPLICE_EXPIRED, CTaskCountersProcessor::COUNTER_TASKS_AUDITOR_EXPIRED, CTaskCountersProcessor::COUNTER_TASKS_ORIGINATOR_EXPIRED, CTaskCountersProcessor::COUNTER_TASKS_MY_EXPIRED_CANDIDATES, CTaskCountersProcessor::COUNTER_TASKS_ACCOMPLICE_EXPIRED_CANDIDATES), true)) {
         $isExpirityCounter = true;
     } else {
         $isExpirityCounter = false;
     }
     $isCounterBrokeDetected = false;
     $realTasksCount = null;
     // Is checksum correct?
     $filterCheksum = $arFilter['::MARKERS'][self::MARKER_ID]['filterCheksum'];
     $realCheksum = self::calcFilterChecksum($arFilter);
     // break detection part
     if ($filterCheksum === $realCheksum) {
         $realTasksCount = $tasksCountInList;
         if ($counterValue < 0 || $tasksCountInList != $counterValue) {
             $isCounterBrokeDetected = true;
         }
     } else {
         if (isset($arFilter['SAME_GROUP_PARENT'], $arFilter['ONLY_ROOT_TASKS']) && $arFilter['SAME_GROUP_PARENT'] === 'Y' && $arFilter['ONLY_ROOT_TASKS'] === 'Y') {
             // unset the corresponding fields and try to compare checksums again
             unset($arFilter['SAME_GROUP_PARENT']);
             unset($arFilter['ONLY_ROOT_TASKS']);
             $realCheksum = self::calcFilterChecksum($arFilter);
             if ($filterCheksum === $realCheksum) {
                 // tasks count in list shouldn't be more than registered in counter
                 // and counter shouldn't be less than zero
                 if ($counterValue < 0 || $tasksCountInList > $counterValue) {
                     $isCounterBrokeDetected = true;
                 } else {
                     if (static::getCountersRecheckForSubTasksNeed()) {
                         $rsTasksCount = CTasks::getCount($arFilter, array('bIgnoreDbErrors' => true, 'bSkipUserFields' => true, 'bSkipExtraTables' => true));
                         if ($rsTasksCount && ($arTasksCount = $rsTasksCount->fetch()) && isset($arTasksCount['CNT'])) {
                             $realTasksCount = (int) $arTasksCount['CNT'];
                             if ($realTasksCount != $counterValue) {
                                 // and finally check
                                 $isCounterBrokeDetected = true;
                             }
                         }
                     }
                 }
             }
         }
     }
     /*
     if ( ! $isCounterBrokeDetected )
     {
     	if ($counterValue < 0)
     	{
     		$isCounterBrokeDetected = true;
     	}
     	else if ($realTasksCount !== null)
     	{
     		if ($isExpirityCounter)
     		{
     			if ($realTasksCount < $counterValue)
     				$isCounterBrokeDetected = true;
     		}
     		else
     		{
     			if ($realTasksCount !== $counterValue)
     				$isCounterBrokeDetected = true;
     		}
     	}
     }
     */
     if ($isCounterBrokeDetected) {
         ob_start();
         // a special way for correction of 'deadline expired' counters
         if ($isExpirityCounter) {
             // pend counters reinstalling (agent is used)
             self::pendCountersRecalculation();
         } else {
             if ($realTasksCount !== null) {
                 $delta = $realTasksCount - $counterValue;
                 CTaskCountersQueue::push($counterId, CTaskCountersQueue::OP_INCREMENT, array($counterOwnerUserId), $delta);
                 CTaskCountersQueue::execute();
             } else {
                 CTaskAssert::logError('[0x97e63b37] counter "' . $counterId . '" was mistimed for user ' . $counterOwnerUserId . '. But no correct data available for recount.');
             }
         }
         ob_end_clean();
     }
 }
Пример #30
0
 /**
  * prevent creating through "new"
  *
  * @param $userId
  */
 private function __construct($userId)
 {
     global $USER;
     CTaskAssert::assertLaxIntegers($userId);
     CTaskAssert::assert($userId > 0);
     $this->userId = $userId;
     if (isset($GLOBALS['USER']) && is_object($GLOBALS['USER']) && $USER->IsAuthorized()) {
         $this->loggedInUserId = (int) $USER->getId();
     }
     $this->oListState = CTaskListState::getInstance($userId);
 }