Example #1
0
 /**
  * Test the setType() function
  *
  * @return  void
  */
 public function testSetType()
 {
     $this->handler->setType('Article');
     // Test if the current Type is 'Article'
     $this->assertEquals($this->handler->getType(), 'Article');
     // Test if the Type fallbacks to 'Thing' Type
     $this->handler->setType('TypeThatDoesNotExist');
     $this->assertEquals($this->handler->getType(), $this->defaultType);
 }
 /**
  * Called on cart checkout.
  *
  * @param Cart $cart Cart.
  */
 public function onCheckout($cart)
 {
     if (!isset($this->creditCard)) {
         throw new CheckoutException('Credit Card is not set.', 0);
     }
     if (!in_array($this->creditCard->getType(), $this->validTypes)) {
         throw new CheckoutException('Credit Card is not supported.', 1);
     }
     if ($this->getPatternType($this->creditCard->getNumber()) != $this->creditCard->getType()) {
         throw new CheckoutException('Credit Card is invalid.', 2);
     }
 }
Example #3
0
 /**
  * Wether or not the token can close this block
  * context
  *
  * @param object $token
  * @return bool
  */
 public function canClose($token)
 {
     if (in_array($token->getType(), $this->context['close_on'])) {
         return true;
     }
     return false;
 }
Example #4
0
 /**
  * Creates a new logger instance based on the passed logger configuration.
  *
  * @param object $loggerNode The logger configuration
  *
  * @return \Psr\Log\LoggerInterface The logger instance
  */
 public static function factory($loggerNode)
 {
     // initialize the processors
     $processors = array();
     /** @var \AppserverIo\Appserver\Core\Api\Node\ProcessorNode $processorNode */
     foreach ($loggerNode->getProcessors() as $processorNode) {
         $reflectionClass = new \ReflectionClass($processorNode->getType());
         $processors[] = $reflectionClass->newInstanceArgs($processorNode->getParamsAsArray());
     }
     // initialize the handlers
     $handlers = array();
     /** @var \AppserverIo\Appserver\Core\Api\Node\HandlerNode $handlerNode */
     foreach ($loggerNode->getHandlers() as $handlerNode) {
         // initialize the handler node
         $reflectionClass = new \ReflectionClass($handlerNode->getType());
         $handler = $reflectionClass->newInstanceArgs($handlerNode->getParamsAsArray());
         // if we've a formatter, initialize the formatter also
         if ($formatterNode = $handlerNode->getFormatter()) {
             $reflectionClass = new \ReflectionClass($formatterNode->getType());
             $handler->setFormatter($reflectionClass->newInstanceArgs($formatterNode->getParamsAsArray()));
         }
         // add the handler
         $handlers[] = $handler;
     }
     // prepare the logger params
     $loggerParams = array($loggerNode->getChannelName(), $handlers, $processors);
     $loggerParams = array_merge($loggerParams, $loggerNode->getParamsAsArray());
     // initialize the logger instance itself
     $reflectionClass = new \ReflectionClass($loggerNode->getType());
     $loggerInstance = $reflectionClass->newInstanceArgs($loggerParams);
     // return the instance
     return $loggerInstance;
 }
Example #5
0
 /**
  * Check permission and redirect on error
  * 
  * @param string $a_perm
  * @param string $a_cmd
  * @param string $a_type
  * @param int $a_ref_id
  * @return bool
  */
 protected function checkPermission($a_perm, $a_cmd = "", $a_type = "", $a_ref_id = null)
 {
     if (!$this->checkPermissionBool($a_perm, $a_cmd, $a_type, $a_ref_id)) {
         if (!is_int(strpos($_SERVER["PHP_SELF"], "goto.php"))) {
             // create: redirect to parent
             if ($a_perm == "create") {
                 if (!$a_ref_id) {
                     $a_ref_id = $_GET["ref_id"];
                 }
                 $type = ilObject::_lookupType($a_ref_id, true);
             } else {
                 // does this make sense?
                 if (!is_object($this->object)) {
                     return;
                 }
                 if (!$a_ref_id) {
                     $a_ref_id = $this->object->getRefId();
                 }
                 $type = $this->object->getType();
             }
             ilSession::clear("il_rep_ref_id");
             ilUtil::sendFailure($this->lng->txt("permission_denied"), true);
             ilUtil::redirect("goto.php?target=" . $type . "_" . $a_ref_id);
         } else {
             die("Permission Denied.");
         }
     }
 }
 /**
  * Don't allow having axis or identifier as value in the product template
  *
  * @param object     $group
  * @param Constraint $constraint
  */
 public function validate($group, Constraint $constraint)
 {
     if ($group instanceof GroupInterface && $group->getType()->isVariant()) {
         if ($group->getProductTemplate() !== null) {
             $this->validateProductTemplateValues($group, $constraint);
         }
     }
 }
 /**
  * Don't allow having multiple products with same combination of values for axis of the variant group
  *
  * @param object     $entity
  * @param Constraint $constraint
  */
 public function validate($entity, Constraint $constraint)
 {
     if ($entity instanceof GroupInterface && $entity->getType()->isVariant()) {
         $this->validateVariantGroup($entity, $constraint);
     } elseif ($entity instanceof ProductInterface) {
         $this->validateProduct($entity, $constraint);
     }
 }
 /**
  * Get an array of object properties.
  *
  * @param object           $value
  * @param \ReflectionClass $class
  * @param int              $propertyFilter One of \ReflectionProperty constants
  *
  * @return array
  */
 protected function getProperties($value, \ReflectionClass $class, $propertyFilter)
 {
     $props = array();
     $props['type'] = $value->getType();
     $props['attributes'] = $value->getAttributes();
     foreach ($value->getSubNodeNames() as $name) {
         $props[$name] = $value->{$name};
     }
     return $props;
 }
 /**
  * Decorate Notifier
  *
  * Automatically attach the decorate toolbar if the delegate has previously already been attached. This will
  * subscribe the decorator to the event dispatcher.
  *
  * @param object $delegate The object being decorated
  * @return void
  * @throws  \InvalidArgumentException If the delegate is not an object
  * @see ControllerToolbarMixin::attachToolbar()
  */
 public function onDecorate($delegate)
 {
     $controller = $delegate->getController();
     if ($controller->inherits('Nooku\\Library\\ControllerToolbarMixin')) {
         if ($controller->hasToolbar($delegate->getType())) {
             $controller->detachToolbar($delegate);
             $controller->attachToolbar($this);
         }
     }
     parent::onDecorate($delegate);
 }
Example #10
0
 /**
  * Decorate Notifier
  *
  * Automatically attach the decorate toolbar if the delegate has previously already been attached. This will
  * subscribe the decorator to the event dispatcher.
  *
  * @param object $delegate The object being decorated
  * @return void
  * @throws  \InvalidArgumentException If the delegate is not an object
  * @see ControllerToolbarMixin::attachToolbar()
  */
 public function onDecorate($delegate)
 {
     $controller = $delegate->getController();
     if ($controller->inherits('KControllerToolbarMixin')) {
         if ($controller->hasToolbar($delegate->getType())) {
             $controller->removeToolbar($delegate);
             $controller->addToolbar($this);
         }
     }
     parent::onDecorate($delegate);
 }
 /**
  * @param  object                                                $group
  * @param  null                                                  $format
  * @param  array                                                 $context
  * @return array|\Symfony\Component\Serializer\Normalizer\scalar
  */
 public function normalize($group, $format = null, array $context = [])
 {
     /**@var Group $group * */
     $normalizedGroup = ['code' => $group->getCode(), 'type' => $group->getType()->getCode()];
     foreach ($group->getTranslations() as $trans) {
         $normalizedGroup['labels'][$trans->getLocale()] = $trans->getLabel();
     }
     foreach ($group->getAttributes() as $attr) {
         $normalizedGroup['attributes'][] = $attr->getCode();
     }
     return $normalizedGroup;
 }
Example #12
0
 /**
  * Decorate Notifier
  *
  * Automatically attach the decorate toolbar if the delegate has previously already been attached. This will
  * subscribe the decorator to the event dispatcher.
  *
  * @param object $delegate The object being decorated
  * @return void
  * @throws  \InvalidArgumentException If the delegate is not an object
  * @see ControllerToolbarMixin::attachToolbar()
  */
 public function onDecorate($delegate)
 {
     $controller = $delegate->getController();
     if ($controller->isCommandable()) {
         $type = $delegate->getType();
         if ($controller->hasToolbar($type)) {
             $controller->removeToolbar($delegate);
             $controller->addToolbar($this);
         }
     }
     parent::onDecorate($delegate);
 }
 /**
  * Normalizes an object into a set of arrays/scalars.
  *
  * @param object $object object to normalize
  * @param string $format format the normalization result will be encoded as
  * @param array $context Context options for the normalizer
  *
  * @return array|string|bool|int|float|null
  */
 public function normalize($object, $format = null, array $context = array())
 {
     /** @var Payer $object */
     $hasComments = true;
     $comments = $object->getComments();
     if (is_null($comments) || $comments->getSize() == 0) {
         $hasComments = false;
     } else {
         $comments = $comments->getComments();
     }
     return array_filter(array('@type' => $object->getType(), '@ref' => $object->getRef(), 'title' => $object->getTitle(), 'firstname' => $object->getFirstName(), 'surname' => $object->getSurname(), 'company' => $object->getCompany(), 'address' => $object->getAddress(), 'phonenumbers' => $object->getPhoneNumbers(), 'email' => $object->getEmail(), 'comments' => $hasComments ? array('comment' => $comments) : array()), array(NormaliserHelper::GetClassName(), "filter_data"));
 }
 /**
  * Axis must be provided for new variant group
  *
  * @param object     $variantGroup
  * @param Constraint $constraint
  */
 public function validate($variantGroup, Constraint $constraint)
 {
     /** @var GroupInterface */
     if ($variantGroup instanceof GroupInterface) {
         $isNew = $variantGroup->getId() === null;
         $isVariantGroup = $variantGroup->getType()->isVariant();
         $hasAxis = count($variantGroup->getAxisAttributes()) > 0;
         if ($isNew && $isVariantGroup && !$hasAxis) {
             $this->context->addViolation($constraint->expectedAxisMessage, array('%variant group%' => $variantGroup->getCode()));
         } elseif (!$isVariantGroup && $hasAxis) {
             $this->context->addViolation($constraint->unexpectedAxisMessage, array('%group%' => $variantGroup->getCode()));
         }
     }
 }
Example #15
0
 /**
  * Given an instance of a CUploadedFile, make a FileModel, save it, and return it.
  * If the file is empty, an exception is thrown otherwise the fileModel is returned.
  * @param object $uploadedFile CUploadedFile
  */
 public static function makeByUploadedFile($uploadedFile)
 {
     assert('$uploadedFile instanceof CUploadedFile');
     $fileContent = new FileContent();
     $fileContent->content = file_get_contents($uploadedFile->getTempName());
     $file = new FileModel();
     $file->fileContent = $fileContent;
     $file->name = $uploadedFile->getName();
     $file->type = $uploadedFile->getType();
     $file->size = $uploadedFile->getSize();
     if (!$file->save()) {
         throw new FailedFileUploadException(Zurmo::t('ZurmoModule', 'File failed to upload. The file is empty.'));
     }
     return $file;
 }
 /**
  * Get array from object
  *
  * @param array|object $data
  *
  * @return array
  */
 protected function toArrayRecursive($data)
 {
     $type = $data->getType();
     if (is_array($data->getValue())) {
         $result = [self::TYPE_LIST => [], 'type' => self::TYPE_LIST];
         foreach ($data->getValue() as $key => $value) {
             if ($value instanceof $this) {
                 $result[self::TYPE_LIST][] = $data->toArrayRecursive($value);
             }
         }
         return $result;
     } else {
         return [$type => $data->getValue(), 'type' => $type];
     }
 }
 /**
  * Axis must be provided for new variant group
  *
  * @param object     $variantGroup
  * @param Constraint $constraint
  */
 public function validate($variantGroup, Constraint $constraint)
 {
     /* @var GroupInterface */
     if ($variantGroup instanceof GroupInterface) {
         $isNew = null === $variantGroup->getId();
         $isVariantGroup = $variantGroup->getType()->isVariant();
         $hasAxis = count($variantGroup->getAxisAttributes()) > 0;
         if ($isNew && $isVariantGroup && !$hasAxis) {
             $this->addExpectedAxisViolation($constraint, $variantGroup->getCode());
         } elseif ($isVariantGroup && $hasAxis) {
             $this->validateAttributeAxis($constraint, $variantGroup);
         } elseif (!$isVariantGroup && $hasAxis) {
             $this->addUnexpectedAxisViolation($constraint, $variantGroup->getCode());
         }
     }
 }
 public function analyzePage()
 {
     $data = $this->dataProvider->getData(true);
     foreach ($data as $rowBean) {
         assert('$rowBean->id != null');
         $columnMessages = array();
         $shouldSkipRow = false;
         foreach ($this->sanitizableColumnNames as $columnName) {
             $attributeIndexOrDerivedType = $this->mappingData[$columnName]['attributeIndexOrDerivedType'];
             $penultimateModelClassName = ImportUtil::getPenultimateModelClassNameByImportRules($this->importRules);
             $attributeImportRules = AttributeImportRulesFactory::makeByImportRulesTypeAndAttributeIndexOrDerivedType($this->importRules->getType(), $attributeIndexOrDerivedType, $penultimateModelClassName);
             $modelClassName = $attributeImportRules->getModelClassName();
             $attributeName = static::resolveAttributeNameByRules($attributeImportRules);
             if (null != ($attributeValueSanitizerUtilTypes = $attributeImportRules->getSanitizerUtilTypesInProcessingOrder())) {
                 assert('is_array($attributeValueSanitizerUtilTypes)');
                 foreach ($attributeValueSanitizerUtilTypes as $attributeValueSanitizerUtilType) {
                     $sanitizer = ImportSanitizerUtilFactory::make($attributeValueSanitizerUtilType, $modelClassName, $attributeName, $columnName, $this->mappingData[$columnName], null, $penultimateModelClassName, $attributeIndexOrDerivedType);
                     $sanitizer->analyzeByRow($rowBean);
                     if ($sanitizer->getShouldSkipRow()) {
                         $shouldSkipRow = true;
                     }
                     foreach ($sanitizer->getAnalysisMessages() as $message) {
                         $columnMessages[$columnName][] = $message;
                     }
                     $classToEvaluate = new ReflectionClass($sanitizer);
                     if ($classToEvaluate->implementsInterface('ImportSanitizerHasCustomFieldValuesInterface')) {
                         $missingCustomFieldValues = $sanitizer->getMissingCustomFieldValues();
                         $this->getCustomFieldsInstructionData()->addMissingValuesByColumnName($missingCustomFieldValues, $columnName);
                     }
                 }
             }
         }
         if (!empty($columnMessages)) {
             $rowBean->serializedAnalysisMessages = serialize($columnMessages);
             if ($shouldSkipRow) {
                 $rowBean->analysisStatus = static::STATUS_SKIP;
             } else {
                 $rowBean->analysisStatus = static::STATUS_WARN;
             }
         } else {
             $rowBean->serializedAnalysisMessages = null;
             $rowBean->analysisStatus = static::STATUS_CLEAN;
         }
         ZurmoRedBean::store($rowBean);
     }
 }
 /**
  * @param array|object $item       The item
  * @param string       $columnName The column name
  *
  * @return mixed
  */
 public function getValue($item, $columnName)
 {
     if ($columnName == 'title') {
         return $item->getDisplayTitle();
     } elseif ($columnName == 'online') {
         return $item;
     } elseif ($columnName == 'type') {
         if ($item->getType() == MenuItem::TYPE_PAGE_LINK) {
             return 'Page link';
         } else {
             return 'External link';
         }
     } elseif ($columnName == 'url') {
         return $item;
     }
     return parent::getValue($item, $columnName);
 }
/**
 * Filters a new comment post and sends email replies to previous posters
 * @param object $comment the comment
 * @param object $owner the element commented upon.
 */
function emailReply($comment, $owner)
{
    $gallery = new Gallery();
    if ($comment->getInModeration() || $comment->getPrivate()) {
        return $comment;
        // we are not going to e-mail unless the comment has passed.
    }
    $oldcomments = $owner->comments;
    $emails = array();
    foreach ($oldcomments as $oldcomment) {
        $name = $oldcomment['name'];
        $emails[$name] = $oldcomment['email'];
    }
    $emails = array_unique($emails);
    switch ($comment->getType()) {
        case "albums":
            $url = "album=" . urlencode($owner->name);
            $action = sprintf(gettext('A reply has been posted on album "%1$s".'), $owner->name);
            break;
        case "news":
            $url = "p=" . ZENPAGE_NEWS . "&title=" . urlencode($owner->getTitlelink());
            $action = sprintf(gettext('A reply has been posted on article "%1$s".'), $owner->getTitlelink());
            break;
        case "pages":
            $url = "p=" . ZENPAGE_PAGES . "&title=" . urlencode($owner->getTitlelink());
            $action = sprintf(gettext('A reply has been posted on page "%1$s".'), $owner->getTitlelink());
            break;
        default:
            // all image types
            $url = "album=" . urlencode($owner->album->name) . "&image=" . urlencode($owner->filename);
            $action = sprintf(gettext('A reply has been posted on "%1$s" the album "%2$s".'), $owner->getTitle(), $owner->getAlbumName());
    }
    if ($comment->getAnon()) {
        $email = $name = '<' . gettext("Anonymous") . '>';
    } else {
        $name = $comment->getname();
        $email = $comment->getEmail();
    }
    $message = $action . "\n\n" . sprintf(gettext('Author: %1$s' . "\n" . 'Email: %2$s' . "\n" . 'Website: %3$s' . "\n" . 'Comment:' . "\n\n" . '%4$s'), $name, $email, $comment->getWebsite(), $comment->getComment()) . "\n\n" . sprintf(gettext('You can view all comments about this item here:' . "\n" . '%1$s'), 'http://' . $_SERVER['SERVER_NAME'] . WEBPATH . '/index.php?' . $url) . "\n\n";
    $on = gettext('Reply posted');
    zp_mail("[" . $gallery->getTitle() . "] {$on}", $message, $emails);
    return $comment;
}
 /**
  * Returns the type of a column.
  *
  * @param  object $column A column object
  *
  * @return string The column type
  */
 public function getType($column)
 {
     if ($column->isForeignKey()) {
         return 'ForeignKey';
     }
     switch ($column->getType()) {
         case PropelColumnTypes::BOOLEAN:
         case PropelColumnTypes::BOOLEAN_EMU:
             return 'Boolean';
         case PropelColumnTypes::DATE:
         case PropelColumnTypes::TIMESTAMP:
             return 'Date';
         case PropelColumnTypes::TIME:
             return 'Time';
         default:
             return 'Text';
     }
 }
Example #22
0
/**
 * Log a system event related to a specific object.
 *
 * This is called by the event system and should not be called directly.
 *
 * @param object $object The object you're talking about.
 * @param string $event  String The event being logged
 *
 * @return mixed
 */
function system_log($object, $event)
{
    global $CONFIG;
    static $log_cache;
    static $cache_size = 0;
    if ($object instanceof Loggable) {
        // reset cache if it has grown too large
        if (!is_array($log_cache) || $cache_size > 500) {
            $log_cache = array();
            $cache_size = 0;
        }
        // Has loggable interface, extract the necessary information and store
        $object_id = (int) $object->getSystemLogID();
        $object_class = $object->getClassName();
        $object_type = $object->getType();
        $object_subtype = $object->getSubtype();
        $event = sanitise_string($event);
        $time = time();
        $ip_address = sanitise_string($_SERVER['REMOTE_ADDR']);
        $performed_by = elgg_get_logged_in_user_guid();
        if (isset($object->access_id)) {
            $access_id = $object->access_id;
        } else {
            $access_id = ACCESS_PUBLIC;
        }
        if (isset($object->enabled)) {
            $enabled = $object->enabled;
        } else {
            $enabled = 'yes';
        }
        if (isset($object->owner_guid)) {
            $owner_guid = $object->owner_guid;
        } else {
            $owner_guid = 0;
        }
        // Create log if we haven't already created it
        if (!isset($log_cache[$time][$object_id][$event])) {
            $query = "INSERT DELAYED into {$CONFIG->dbprefix}system_log\n\t\t\t\t(object_id, object_class, object_type, object_subtype, event,\n\t\t\t\tperformed_by_guid, owner_guid, access_id, enabled, time_created, ip_address)\n\t\t\tVALUES\n\t\t\t\t('{$object_id}','{$object_class}','{$object_type}', '{$object_subtype}', '{$event}',\n\t\t\t\t{$performed_by}, {$owner_guid}, {$access_id}, '{$enabled}', '{$time}', '{$ip_address}')";
            insert_data($query);
            $log_cache[$time][$object_id][$event] = true;
            $cache_size += 1;
        }
        return true;
    }
}
Example #23
0
 /**
  * Create the main callback method. this method centralizes error processing.
  *
  * the errors we expect are from the pear modules DB, DB_DataObject
  * which currently use PEAR::raiseError to notify of error messages.
  *
  * @param object $pearError PEAR_Error
  *
  * @return void
  */
 public static function handle($pearError)
 {
     // setup smarty with config, session and template location.
     $template = CRM_Core_Smarty::singleton();
     $config = CRM_Core_Config::singleton();
     if ($config->backtrace) {
         self::backtrace();
     }
     // create the error array
     $error = array();
     $error['callback'] = $pearError->getCallback();
     $error['code'] = $pearError->getCode();
     $error['message'] = $pearError->getMessage();
     $error['mode'] = $pearError->getMode();
     $error['debug_info'] = $pearError->getDebugInfo();
     $error['type'] = $pearError->getType();
     $error['user_info'] = $pearError->getUserInfo();
     $error['to_string'] = $pearError->toString();
     // We access connection info via _DB_DATAOBJECT instead
     // of, e.g., calling getDatabaseConnection(), so that we
     // can avoid infinite loops.
     global $_DB_DATAOBJECT;
     if (!isset($_DB_DATAOBJECT['CONFIG']['database'])) {
         // we haven't setup sql, so it's not our sql error...
     } elseif (preg_match('/^mysql:/', $_DB_DATAOBJECT['CONFIG']['database']) && mysql_error()) {
         $mysql_error = mysql_error() . ', ' . mysql_errno();
         $template->assign_by_ref('mysql_code', $mysql_error);
         // execute a dummy query to clear error stack
         mysql_query('select 1');
     } elseif (preg_match('/^mysqli:/', $_DB_DATAOBJECT['CONFIG']['database'])) {
         $dao = new CRM_Core_DAO();
         if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5])) {
             $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5];
             $link = $conn->connection;
             if (mysqli_error($link)) {
                 $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link);
                 $template->assign_by_ref('mysql_code', $mysql_error);
                 // execute a dummy query to clear error stack
                 mysqli_query($link, 'select 1');
             }
         }
     }
     $template->assign_by_ref('error', $error);
     $errorDetails = CRM_Core_Error::debug('', $error, FALSE);
     $template->assign_by_ref('errorDetails', $errorDetails);
     CRM_Core_Error::debug_var('Fatal Error Details', $error);
     CRM_Core_Error::backtrace('backTrace', TRUE);
     if ($config->initialized) {
         $content = $template->fetch('CRM/common/fatal.tpl');
         echo CRM_Utils_System::theme($content);
     } else {
         echo "Sorry. A non-recoverable error has occurred. The error trace below might help to resolve the issue<p>";
         CRM_Core_Error::debug(NULL, $error);
     }
     static $runOnce = FALSE;
     if ($runOnce) {
         exit;
     }
     $runOnce = TRUE;
     self::abend(1);
 }
 /**
  * Standard method for processing relationships
  *
  * @param object $relation            
  * @param array $baseRecord            
  */
 protected function processStandardRelationships($relation, $baseRecord)
 {
     // store parentModels for later use
     $parentModels = $this->getParentModels(true);
     // skip any parent relationships because they are merged into the main record
     $refModelNameSpace = $relation->getReferencedModel();
     if ($parentModels and in_array($refModelNameSpace, $parentModels)) {
     } else {
         $refType = $relation->getType();
         // store a copy of all related record (PKIDs)
         // this must be attached w/ the parent records for joining purposes
         $relatedRecordIds = null;
         $refModel = new $refModelNameSpace();
         $primaryKeyName = $refModel->getPrimaryKeyName();
         // figure out if we have a preferred alias
         $alias = $relation->getAlias();
         if (isset($alias)) {
             $refModelName = $alias;
         } else {
             $refModelName = $relation->getModelName();
         }
         // Check for a bad reference
         if (!isset($baseRecord->{$refModelName})) {
             // TODO throw error here
             throw new HTTPException("A bad relationship reference was encountered.", 500, array('dev' => "Bad reference was: {$this->model->getModelName()} -> {$refModelName}", 'code' => '654981091519894'));
         } else {
             // harmonize relatedRecords
             if ($refType == 0) {
                 $relatedRecords = $this->getBelongsToRecord($relation);
             } elseif ($refType == 1) {
                 // // ignore hasOne since they are processed like a parent relation
                 // // this means current logic will not merg in a parent's record for a hasOne relationship
                 // // it's an edge case but should be supported in the future
                 // continue;
                 // /*
                 // * The following code is not executed
                 // */
                 // // all hasOne relationships would be loaded in the initial query right?
                 // // if the hasOne itself has a parent, then treat it more like a belongsTO so
                 // // merged columns are loaded
                 // $relatedParent = $refModelNameSpace::$parentModel;
                 // if ($relatedParent) {
                 // $relatedRecords = $this->getBelongsToRecord($relation);
                 // } else {
                 // // if a false is detected then load an empty model to takes it's place
                 // // this is likely the result of a left join on a non-existing record
                 // $relatedModel = $baseRecord->$refModelName;
                 // switch ($relatedModel) {
                 // case false:
                 // $relatedModelPath = "\\PhalconRest\\Models\\" . $refModelName;
                 // $emptyModel = new $relatedModelPath();
                 // $relatedRecords = array(
                 // $this->loadAllowedColumns($emptyModel)
                 // );
                 // break;
                 // case null:
                 // // throw error here
                 // break;
                 // default:
                 // $relatedRecords = $this->loadAllowedColumns($relatedModel);
                 // break;
                 // }
                 // }
             } elseif ($refType == 4) {
                 $relatedRecords = $this->getHasManyToManyRecords($relation);
             } else {
                 $relatedRecords = $this->getHasManyRecords($relation);
             }
             if (isset($relatedRecords) && $relatedRecords) {
                 return $this->normalizeRelatedRecords($baseRecord, $relatedRecords, $relation);
             }
             return true;
         }
     }
 }
 /**
  * Import discovered device (add / update data in GLPI DB)
  *
  * @param object $item
  */
 function importDevice($item)
 {
     PluginFusioninventoryLogger::logIfExtradebugAndDebugMode('fusioninventorycommunication', 'Function PluginFusinvsnmpCommunicationNetDiscovery->importDevice().');
     $arrayinventory = $_SESSION['SOURCE_XMLDEVICE'];
     $input = array();
     $input['id'] = $item->getID();
     $a_lockable = PluginFusioninventoryLock::getLockFields(getTableForItemType($item->getType()), $item->getID());
     if (!in_array('name', $a_lockable)) {
         if (isset($arrayinventory['SNMPHOSTNAME']) && !empty($arrayinventory['SNMPHOSTNAME'])) {
             $input['name'] = $arrayinventory['SNMPHOSTNAME'];
         } else {
             if (isset($arrayinventory['NETBIOSNAME']) && !empty($arrayinventory['NETBIOSNAME'])) {
                 $input['name'] = $arrayinventory['NETBIOSNAME'];
             } else {
                 if (isset($arrayinventory['DNSHOSTNAME']) && !empty($arrayinventory['DNSHOSTNAME'])) {
                     $input['name'] = $arrayinventory['DNSHOSTNAME'];
                 }
             }
         }
     }
     if (!in_array('serial', $a_lockable)) {
         if (isset($arrayinventory['SERIAL'])) {
             if (trim($arrayinventory['SERIAL']) != '') {
                 $input['serial'] = trim($arrayinventory['SERIAL']);
             }
         }
     }
     if (isset($input['name']) && $input['name'] == '') {
         unset($input['name']);
     }
     if (isset($input['serial']) && $input['serial'] == '') {
         unset($input['serial']);
     }
     if (isset($arrayinventory['ENTITY']) and !empty($arrayinventory['ENTITY'])) {
         $input['entities_id'] = $arrayinventory['ENTITY'];
         if (!isset($_SESSION['glpiactiveentities_string'])) {
             $_SESSION['glpiactiveentities_string'] = "'" . $arrayinventory['ENTITY'] . "'";
         }
     }
     if (!isset($_SESSION['glpiactiveentities_string'])) {
         $_SESSION['glpiactiveentities_string'] = "'" . $item->fields['entities_id'] . "'";
     }
     switch ($item->getType()) {
         case 'Computer':
             // don't update this computer, if it is already handled by
             // its own agent
             if (Dropdown::getDropdownName("glpi_autoupdatesystems", $item->fields['autoupdatesystems_id']) == 'FusionInventory') {
                 return;
             }
             if (isset($arrayinventory['WORKGROUP'])) {
                 $domain = new Domain();
                 if (!in_array('domains_id', $a_lockable)) {
                     $input['domains_id'] = $domain->import(array('name' => $arrayinventory['WORKGROUP']));
                 }
             }
             $item->update($input);
             $this->_updateNetworkInfo($arrayinventory, 'Computer', $item->getID(), 'NetworkPortEthernet', 1);
             break;
         case 'PluginFusioninventoryUnmanaged':
             // Write XML file
             if (isset($_SESSION['SOURCE_XMLDEVICE'])) {
                 PluginFusioninventoryToolbox::writeXML($input['id'], serialize($_SESSION['SOURCE_XMLDEVICE']), 'PluginFusioninventoryUnmanaged');
             }
             if (!in_array('contact', $a_lockable) && isset($arrayinventory['USERSESSION'])) {
                 $input['contact'] = $arrayinventory['USERSESSION'];
             }
             if (!in_array('domain', $a_lockable)) {
                 if (isset($arrayinventory['WORKGROUP']) && !empty($arrayinventory['WORKGROUP'])) {
                     $input['domain'] = Dropdown::importExternal("Domain", $arrayinventory['WORKGROUP'], $arrayinventory['ENTITY']);
                 }
             }
             if (!empty($arrayinventory['TYPE'])) {
                 switch ($arrayinventory['TYPE']) {
                     case '1':
                     case 'COMPUTER':
                         $input['item_type'] = 'Computer';
                         break;
                     case '2':
                     case 'NETWORKING':
                         $input['item_type'] = 'NetworkEquipment';
                         break;
                     case '3':
                     case 'PRINTER':
                         $input['item_type'] = 'Printer';
                         break;
                 }
             }
             $input['plugin_fusioninventory_agents_id'] = $_SESSION['glpi_plugin_fusioninventory_agentid'];
             $this->_updateSNMPInfo($arrayinventory, $input, $item);
             $this->_updateNetworkInfo($arrayinventory, 'PluginFusioninventoryUnmanaged', $item->getID(), 'NetworkPortEthernet', 1);
             break;
         case 'NetworkEquipment':
             // Write XML file
             if (isset($_SESSION['SOURCE_XMLDEVICE'])) {
                 PluginFusioninventoryToolbox::writeXML($input['id'], serialize($_SESSION['SOURCE_XMLDEVICE']), 'NetworkEquipment');
             }
             $item->update($input);
             $this->_updateNetworkInfo($arrayinventory, 'NetworkEquipment', $item->getID(), 'NetworkPortAggregate', 0);
             $pfNetworkEquipment = new PluginFusioninventoryNetworkEquipment();
             $input = $this->_initSpecificInfo('networkequipments_id', $item->getID(), $pfNetworkEquipment);
             $this->_updateSNMPInfo($arrayinventory, $input, $pfNetworkEquipment);
             break;
         case 'Printer':
             // Write XML file
             if (isset($_SESSION['SOURCE_XMLDEVICE'])) {
                 PluginFusioninventoryToolbox::writeXML($input['id'], serialize($_SESSION['SOURCE_XMLDEVICE']), 'Printer');
             }
             $input['have_ethernet'] = '1';
             $item->update($input);
             $this->_updateNetworkInfo($arrayinventory, 'Printer', $item->getID(), 'NetworkPortEthernet', 1);
             $pfPrinter = new PluginFusioninventoryPrinter();
             $input = $this->_initSpecificInfo('printers_id', $item->getID(), $pfPrinter);
             $this->_updateSNMPInfo($arrayinventory, $input, $pfPrinter);
             break;
     }
 }
Example #26
0
 /**
  * Boolean function to determine if this is a one form page.
  *
  * @return bool
  */
 public function isSimpleForm()
 {
     return $this->_state->getType() & (CRM_Core_State::START | CRM_Core_State::FINISH);
 }
 /**
  * Normalizes an object into a set of arrays/scalars.
  *
  * @param object $object object to normalize
  * @param string $format format the normalization result will be encoded as
  * @param array $context Context options for the normalizer
  *
  * @return array|string|bool|int|float|null
  */
 public function normalize($object, $format = null, array $context = array())
 {
     /** @var Address $object */
     return array_filter(array('@type' => $object->getType(), 'code' => $object->getCode(), 'country' => $object->getCountry()));
 }
Example #28
0
 /**
  * @param object $object
  * @return string
  */
 protected function getEntityClass($object)
 {
     if ($object instanceof ObjectIdentityInterface) {
         $class = $object->getType();
     } else {
         $class = $this->doctrineHelper->getEntityClass($object);
     }
     return ClassUtils::getRealClass($class);
 }
Example #29
0
 /**
  * Quotes the column value to help prevent SQL injection attacks.
  *
  * This method makes educated guesses on the scalar type based on the
  * passed value. Make sure to correctly cast the value and/or pass the
  * $column parameter to get the best results.
  *
  * @param mixed $value    The scalar value to quote, a Horde_Db_Value,
  *                        Horde_Date, or DateTime instance, or an object
  *                        implementing quotedId().
  * @param object $column  An object implementing getType().
  *
  * @return string  The correctly quoted value.
  */
 public function quote($value, $column = null)
 {
     if (is_object($value) && is_callable(array($value, 'quotedId'))) {
         return $value->quotedId();
     }
     if ($value instanceof Horde_Db_Value) {
         return $value->quote($this->_adapter);
     }
     $type = isset($column) ? $column->getType() : null;
     if (is_null($value)) {
         return 'NULL';
     } elseif ($value === true) {
         return $type == 'integer' ? '1' : $this->quoteTrue();
     } elseif ($value === false) {
         return $type == 'integer' ? '0' : $this->quoteFalse();
     } elseif (is_float($value)) {
         return sprintf('%F', $value);
     } elseif (is_int($value)) {
         return $value;
     } elseif ($value instanceof DateTime || $value instanceof Horde_Date) {
         return $this->_adapter->quoteString($type == 'integer' ? $value->format('U') : $value->format('Y-m-d H:i:s'));
     } elseif ($type == 'integer') {
         return (int) $value;
     } elseif ($type == 'float') {
         return sprintf('%F', $value);
     } else {
         return $this->_adapter->quoteString($value);
     }
 }
 /**
  * Normalizes an object into a set of arrays/scalars.
  *
  * @param object $object object to normalize
  * @param string $format format the normalization result will be encoded as
  * @param array $context Context options for the normalizer
  *
  * @return array|string|bool|int|float|null
  */
 public function normalize($object, $format = null, array $context = array())
 {
     /** @var DccInfo $object */
     return array_filter(array('ccp' => $object->getDccProcessor(), 'type' => $object->getType(), 'rate' => $object->getRate(), 'ratetype' => $object->getRateType(), 'amount' => $object->getAmount()), array(NormaliserHelper::GetClassName(), "filter_data"));
 }